0% found this document useful (0 votes)
27 views25 pages

C Unit1

Uploaded by

manasa rai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views25 pages

C Unit1

Uploaded by

manasa rai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

1

UNIT – I
OVERVIEW OF C
C is a structured, high-level machine independent language. It allows software
developers to develop programs without worrying about the hardware platforms
where they will be implemented.

History of C
● ALGOL:
The root of all modern language, introduced in 1960s. It was the first computer
language to use the block structure.It gave the concept of structured
programming to computer science community.
● In 1967, Martin Richards developed a language called BCPL (Basic Combin
Programming Language) for writing system software.
● In 1970, Ken Thompson created a language using the features of BCPL and
named it as ‘B’.
● In 1972, C was evolved from ALGOL, BCPL and B by Dennis Ritchie at the Bell
Laboratories.
● In 1978, Dennis Ritchie and Brian Kernighan published the first edition
book, “The C Programming Language” and commonly known as K&R C
● 1983 American National Standard Institute (ANSI) appointed a committee to
define a standard for C.
● In Dec 1989, the committee approved the version of C which is known as ANSI
C.
● In 1990, the version of C was then approved by the International Standard
Organization (ISO) and referred it as C89.
● In 1999, C99 standard – Next revision was published that introduced new
features like advanced data types and other changes.

Importance of C (Features of C)
● It is a robust language whose rich set of built-in functions and operators can be
used to write any complex program.
● Program written in C are efficient due to several variety of data types and
powerful operators.
● The C compiler combines the capabilities of an assembly language with the
feature of high level language. Therefore it is well suited for writing both system
software and business package.
● There are only 32 keywords; several standard functions are available which can
be used for developing program.
● C is highly portable language; this means that C programs written for one
computer system can be run on another system, with little or no modification.
2
3

Basic Structure of C Programs

1. Documentation section :
The documentation section consists of a set of comment lines giving the name
of the program, the author and other details, which the
programmer would like to use later.
The comments are non executable statements which help the programmers and other
users in understanding various functions and operations of the program. The single
line comments begin with // and multi-line comments enclosed between /* and */
2. Link section :
The link section provides instructions to the compiler to link functions from the
system library.
3. Definition section :
The definition section defines all symbolic constants.
4. Global declaration section :
4

There are some variables that are used in more than one function. Such
variables are called global variables and are declared in the global declaration
section that is outside of all the functions.
5

5. main () function section :


Every C program must have one main function section. This section contains
two parts; declaration part and executable part

Declaration part :The declaration part declares all the variables used in the executable
part.

Executable part :There is at least one statement in the executable part. It contains a
set of instructions to perform the given task.

These two parts must appear between the opening and closing braces. The program
execution begins at the opening brace and ends at the closing brace. The closing
brace of the main function is the logical end of the program. All statements in the
declaration and executable part end with a semicolon.

6. Subprogram section :
The subprogram section contains all the user-defined functions that are called in
the main () function. User-defined functions are generally placed immediately after
the main () function, although they may appear in any order.

NOTE:

● All section, except the main () function and linker section may be absent when
they are not required.

● C is case sensitive. Program statements should be written in lowercase letters


only.

A Sample C Program
Example-1:
#include<stdio.h>
void main()
{
/* -------- Printing Begins -------- */
printf("Hello, Students, This is Our First C Program");
/* -------- Printing Ends -------- */
}

In the above program, main() is a special function. The execution of the program
begins at this line. The empty pair of parenthesis immediately following main
indicates that the function main has no arguments (or parameters). The opening
brace “{“in the second line marks the beginning of the function main and the closing
brace “}” in the last line indicates the end of the function. All the statements
between these two braces form the function body. The function body contains a set
of instructions to perform the given task.
6

In the above example, the function body contains three statements, out of which only
the printf line is an executable statement. The lines beginning with /* and ending
with */ are known as “comments”. Comment lines are not executable statements and
are ignored by the compiler. Comment lines help the programmers and other users in
understanding various functions and operations of the program. The fourth line in the
above program is a printf line. Printf is a pre-defined standard ‘C’ function used for
printing the output on the screen. The output of the above program will be

Hello, Students, This is Our First C Program

Note: Every program must have one main function. If a program contains more than
one main function, the computer gives error message.

Example-2:
/* Program to add two numbers */
#include<stdio.h>
void main()
{
int number;
float amount;
float total;
number = 100;
amount = 30.75;
total = number + amount;
printf("%d \n", number);
printf("%f \n", amount);
printf("%f \n", total);
}

Output: 100
30.75
130.75

The first line of the program is a comment line. number, amount, total are variable
names, int and float are the keywords which represent the data type of the variable.
Since we have declared that int number, the variable number stores integer type of
data and since we have declared that float amount, the variable amount stores
floating point type of data. In C, all variables should be declared to tell the compiler
what is the name of the variable and what is the type of data they hold. The variables
must be declared before they are used.
The statements number=100; amount=30.75; are called assignment statements. The
next statement is an output statement that prints the value of number on the screen.
The statementprintf("%d \n", number); contains two arguments. The first argument
“%d” tells the compiler that the value to be printed is an integer. In the next printf
statement, the argument “%f” tells the compiler that the value of the second
argument total is a floating point number.
7
8

Executing a ‘C’ Program


It involves a series of steps.
1. Creating the program
2. Compiling the program
3. Linking the program with C standard library
4. Executing the program.
Figure 1.3 illustrates the process of creating, compiling and executing a C program.
9
10

C Programming Basic Concepts


A programming language is designed to help process certain kinds of data consisting
of numbers, characters and strings to provide useful output known as information.
The task of processing of data is accomplished by executing a sequence of
instructions called a program. These instructions are formed using certain symbols
and words according to some rigid rules known as syntax rules ( or grammar).

Character Set
The characters that can be used to form words, numbers and expressions depend
upon the computer on which the program is run.
The characters in C are grouped into the following categories.
1. Letters: Uppercase A..Z and Lowercase a…z.
2. Digits: All decimal digits 0…9.
3. Special Characters: ‘, . ; : ? “ ! | / \ ~ _ $ % & ^ * + - <> () {} [] #
4. White Spaces: Blank space, Horizontal tabs, carriage return, new line, form feed.

[Note: Compiler ignores white spaces unless they are part of a string constant. White
spaces may be use to separate words, but are prohibited between the characters of
keywords and identifiers. ]

C Tokens

The smallest individual unit in a C program is called C tokens. There are 6 types of
tokens in C.
• Keywords
• Identifiers
• Constants
• Strings
• Special Symbols
• Operators

Keywords
● Keywords have fixed meanings and these meanings cannot be
changed.
● Keywords are building blocks for program
statements.
● The keywords are also known as reserved words.
● All keywords must be written in lowercase.

There are 32 keywords in C. Some of them are:


11

Identifiers:
Identifiers are used to the names of variables, functions and arrays. They are
user-defined names and consist of a sequence of letters and digits, with a
letter as first character. Both uppercase and lowercase are permitted.The
underscore character is also allowed as a C identifier, usually as a link
between two words in long identifiers
• Rules for Identifiers
1. First Character must be an alphabet (or underscore).
2. Must consists of only letters, digits or underscore.
3. Only first 31 characters are significant.
4. cannot use a keyword.
5. must not contain white space.

Constants:
Constants in C refer to fixed values that do not change during the execution
of a program. Constants can be divided as below.
12

a. Integer Constants: Integer constant refers to a group of digits without


fractional part. There are three types of integers—decimal, octal and
hexadecimal.

i. Decimal integer constant consists of a set of digits 0 through 9, preceded


by
an optional + or – sign. Spaces, commas and non-digit characters are not
permitted between digits.
Valid Example: 123, 25673, -433, 0 etc.
Illegal examples are: 15 750 20,000 $1000.
ii. Octal integer constant consists of combination of digits 0 through 7 with a
leading 0. Example: 037, 0435, 0774 etc.
iii. Hexadecimal integer constant consists of a sequence of digits preceded by
0x or 0X. They may also include alphabets A through F (or a through f).
The letters A through F represent digits 10 through 15. Example: 0X22,
0x9F, 0xAA5

b. Real Constants: Real constants are numbers with fractional part. They are
also called as floating point constants.
A real number can be represented in 2 forms
Decimal notation :
Example: 0.00983, 435.88, -36.33
Exponential notation:
Example: 215.65 = 2.1565 X 102 = 2.1565e2→ This is called the
exponential notation. The general form of exponential notation is

Mantissa e Exponent

Mantissa is either an integer or a real number. The exponent is an


integer number with an optional + or – sign.
Example: 25.5 e3, 572.0 e-2, 101.115 e 12 etc.

c. Single Character Constants: It contains a single character enclosed within a


pair of single quotes. Example: ‘A’, ‘d’, ‘H’ ,’5’ etc.
Note that the character constant ‘5’ is not the same as the number 5.

d. String Constants: A string constant is a sequence of characters enclosed in


double quotes. The characters may be letters, numbers, special characters and
blank space.
Example: “Good Morning!!!”, “I Semester BCA”, “ABCD” etc.

Backslash Character Constants (Escape Sequences):


C Supports some special backslash character constants that are used in
output functions.

Constant Meaning Constant Meaning


\a Bell (beep) \v Vertical tab
\b Back space \’ Single quote
13

\f Form feed \” Double quote


\n New line \? Question mark
\r Carriage return \\ Back slash
\t Horizontal tab \0 Null

Variables
A variable is the symbolic name given to a location in the memory of the
computer where different values are stored. The variable names may consist of
letters, digits and underscore with the following conditions:

1. Variable name must begin with a letter.


2. The variable names can be of length 31 characters. But some compilers
recognize only the first 8 characters. So, generally, variable names should be
of length not more than 8 characters.
3. The variable name should not be a keyword.
4. White space is not allowed.
5. Uppercase and lowercase are significant.
Example:
Valid Variable Names: First_tag, Amount3, Roll_no, Int_type
Invalid Variable Names: char, price$, 21Avg , int

Data types
C supports three main categories of data types.
1. Primary (fundamental) data types.
2. User defined data types.
3. Derived data types.

1. Primary Data types


14

Size and Range of data types

Declaration of Variables
15

Declaration of a variable does two things:


1. It tells the compiler what is the name of the variable.
2. It specifies what type of data the variable will hold.

Primary Type Declaration


A variable can be used to store a value of any data type.

Syntax: data type V1, V2, V3, ….,Vn ;


Here V1, V2, V3, ….,Vn are variable names.
• Variables are separated by commas.
• A declaration statement must end with a semicolon.
Examples: int number;
float amount, total, value;

User Defined Type Declaration


• C supports a feature known as “type definition” that allows users to define an
identifier that would represent an existing data type. This identifier can later be used
to declare variables.
Syntax: typedef type identifier;

Where type refers to an existing data type and “identifier” refers to new name given
to the data type.
Example: typedef int marks;
marks C, FIT, Maths;
Here ‘marks’ is an identifier that represents integer data type. In the second
statement, C, FIT and Maths are defined as marks, which means that they are
defined as integers.

Note: typedef cannot create a new data type. It gives a new name for an existing
data type.

• Another user defined data type is enumerated data

Syntax: enum identifier {value1, value2, ………, valuen };

Where “identifier” is a user defined data type. After this definition, we can declare
variables of type identifier.

Syntax: enum identifier v1, v2, v3, …..vn;


16

The enumerated variables v1, v2, v3, …..vn can only have one of the values value1,
value2, … valuen
Example: enum day {Monday, Tuesday, Wednesday, ……., Sunday}
enum day w;
The compiler automatically assigns integer digits beginning with 0 to all the
enumerated constants. Value1 is assigned 0, value2 is assigned 1 and so on.

Assigning Value to Variables


● Values can be assigned to the variables using the assignment operator
(=) as follows:
Syntax: variable_name = constant;
Example: number=100;
amount=35.75; etc.
• Note: C permits multiple assignments in one line.
Example: number=100; amount=35.75;
• It is also possible to assign a value to a variable at the time of declaration.

Syntax: data type variable_name=constant;


Example: int number=100;
float amount=35.75;
• The process of assigning initial values to variables is called initialization. C
permits initialization of more than one variable in one statement.
Example: p=q=number=100;

Example 3: A Sample C Program


#include <stdio.h>
main()
{
int a = 5, b = 10, c;
c = a *b;
printf(“c = %d”,c)
}
The first line of this program is #include<stdio.h> stdio.h refers to the
standard I/O file containing the standard input and output functions. C
programs are divided into functions. Some functions are written by the user
and many others are stored in C library. If we want to access the functions
stored in the library, it is necessary to tell the compiler about the files to be
accessed.

Example-4: Example of Assignment statements.

#include <stdio.h>
main()
17

{ /* ----- Decleration part ------ */


float x,p;
double y;
unsigned k;
/* ----- Decleration and assignments ------ */
int m=588;
long int n=1234567890;
/* ----- Assignments ------ */
x=1.234567890;
y=9.87654321;
k=54321;
p=1.0;

/* ------ Printing Part ------ */

printf("m=%d \n",m);
printf("n=%ld \n",n);
printf("x=%f \n",x);
printf("y=%lf \n",y);
printf("k=%u \t p=%f \n",k,p);
}

Output:
m = 588
n = 1234567890
x = 1.234567
y =9.87654321
k = 54321 p = 1.000000

Symbolic Constants
A symbolic constant is a name, which substitutes either a numeric constant or a
character, or a string constant. When program is compiled, each occurrence of a
symbolic constant is replaced by its corresponding character sequence. Symbolic
constants are usually defined at the beginning of a program using #define statement.
Syntax: #define symbolic_name constant_value
Example: #define PI 3.142
#define MAX 100
18

Rules regarding #define statement:

1. No blank space between the symbol # and the word define.


2. # must be the first character in that line.
3. A blank space is required between #define and symbolic_name and
constant_value.
4. This statement should not end with a semi colon.
5. After definition, the symbolic name should not be assigned any other value
within the program. For Example, PASS_MARKS=50 is illegal.
6. #define statements may appear anywhere in the program.
7. Symbolic names are not data types. Its data type depends on the type of
Constants

Examples of invalid #define statements


Statement Remark
#define X=35 = sign is not allowed
#define X 25; Semi colon is ot allowed at the
end
# define MAX 10 No whitespace between # and
define
#define N 20, M 10 A statement can define only
one
name
Define should be in lowercase letters.

Reading Data from Keyboard


We can assign values to the variables through the keyboard using the scanf
function.

Syntax: scanf (“control string”, &variable1, &variable2, ….);

The controlstring (or format string) contains the format of data being received. The
ampersand symbol ‘&’ before each variable name is an operator that specifies the
variable name’s address. The variable names are separated by commas.

Example: scanf(“%d”, &num);

When this statement is encountered, the program execution stops and control waits
until a value is typed through the keyboard. Once the value is typed and Enter key is
pressed, program execution continues.

(Refer the Table 2.1 for the different format specifiers of respective data types )

Displaying Output on the Screen


19

We can display the output on the computer screen using printf


function.

Syntax: printf( “control string”, arg1, arg2, ……,argn);

Control string consists of three types of items:

1. Characters that will be printed on the screen as they appear.


2. Format specifications that define the output format for display of each
item.
3. Escape sequence characters such as \n, \t, and \b.

Example: printf(“%d”,sum);

[ Note: The no.of format specifiers and their data type should match with the no.of
arguments mentioned in argument list. ]

Declaring a Variable as a Constant


The value of a variable to remain constant during the execution of the
program the qualifier ‘const’ is used at the time of initialization.

Example: const float PI=3.145;

Const is a new data type qualifier defined by ANSI standard, which tells the
compiler that the value of the float variable PI must not be modified by the
program.

Unformatted I/O Functions


When we use any input output functions in program then we need to include the
header file stdio.h as follows
#include<stdio.h>
The filename stdio.h is an abbreviation for standard input output header file.
The instruction #include<stdio.h> tells the compiler to search for a file named stdio.h
and place its content at this point in the program. The contents of the header file
become part of the source code when it is compiled.

Reading a Character
The getchar() function is used to read single character from the keyboard.
Syntax:
variable_name = getchar();
Where variable_name is a valid C name that is declared as char type. When,
this statement is encountered, the computer waits until a key is pressed and
then assigns this that value to variable_name.
20

Example: char Name;


Name=getchar();

Writing a Character:
The function putchar() is used to display single character contained in a
variable at the terminal.
Syntax:
putchar(variable_name);
Where variable_name is any variable containing a character. This statement
displays the character contained in variable_name at the terminal.
Example:
char answer=’Y’;
putchar(answer);
will display Y on the screen. The statement putchar (‘\n’); would cause the
cursor on the screen to move to the beginning of the next line.

Formatted input
Formatted input refers to an input data that has been arranged in a particular
format. This is possible in C using the scanf() function.(scanf means scan
formatted).
Syntax: scanf(“control string”, arg1, arg2, …., argn);
The control.string specifies the field format in which the data is to be entered and
the arguments arg1, arg2,… , argn specify the address of locations where the data
is stored. Control string and arguments are separated by commas.
Control string (also known as format string) contains field specifications, which
direct the interpretation of input data. It may include:
● Field (or format) specifications, consisting of the conversion character %, a
data type character (or type specifier), and an optional number, specifying
the field width.
● Blanks, tabs, or newlines.
Blanks, tabs and newlines are ignored. The data type character indicates the type
21

of data that is to be assigned to the variable associated with the corresponding


argument. The field width specifier is optional.

Inputting Integer Numbers


The field specification for reading an integer number is: %w d
● The percent sign (%) indicates that a conversion specification follows.
● w is an integer number that specifies the field width of the number to be
read and
● d, known as data type character, indicates that the number to be read is in
integer mode.
Consider the following Example:
scanf (“%2d %5d”, &numl, &num2);

-+Suppose the input data is 50, 31426, the value 50 is assigned to num1 and
31426 to num2.
-Suppose the input,data is 31426 50. The variable num1 will be assigned 31
(because of%2d), and num2 will be assigned 426 (unread, part of 31426). The
value 50 that is unread will be assigned to the first variable in the next scanf call.
-This kind of errors may be eliminated if we use the field specifications without the
field width specifications.
i.e. the statement scanf ("%d %d", &num1, &num2);

 Input data items must be separated by spaces, tabs or newlines.


Punctuation marks do not count as separators. When the scanf function
searches the input data line for a value to be read, it will always bypass any
white space characters.
 If we enter a floating point number instead of an integer, the fractional part
may be skipped away. Also, scanf may skip reading further input.
 When the scanf reads a particular value, reading of the value will be
terminated as soon as the number of characters specified by the field width
is readied (if specified) or until a character that is not valid for the value
being read is encountered. In the case of integers, valid characters are an
optionally signed sequence of digits.
22

Inputting Real Numbers


Unlike integer numbers, the field width of real numbers is not to be specified and
therefore scanf reads real numbers using the simple specification %f for both the
notations, namely, decimal point notation and exponential notation. For example,
the statement
scanf(“%f %f %f”, &x, &y, &z);
with the input data 475.89 43.21E-1 678,
will assign the value 475.89 to x, 4.321 to y, and 678.0 to z.
The input field specifications may be separated by any arbitrary blank spaces.

Inputting Character Strings


We have already seen how a single character can be read from the terminal using
the getchar function. The same can be achieved using the scanf function also.
In addition, a scanf function can input strings containing more than one character.
Following are the specifications for reading character strings:
%ws or %wc
The corresponding argument should be a pointer to a character array. However,
%c may be used to read a single character. when the argument is a pointer to a
char variable then & is not needed, because variable name itself point to the
address location.

Reading Mixed Data Types


It is possible to use one scanf statement to input a data line containing mixed
mode data. In such cases, care should be exercised to ensure that the input data
items match the control specifications in order and type. When an attempt is made
to read an item that does not match the type expected, the scanf function does
not read any further and immediately returns the value read. Example
scanf(“%d %c %f %s”, &count, &code, &ratio, name);

Formatted Output
It is necessary for the programmer to give careful consideration to the appearance
and clarity of the output produced by the program.
The general form of printf statement is
23

printf( “control string”, arg1, arg2, ……,argn);


control string consists of three types of items:
1. Characters that will be printed on the screen as they appear.
2. Format specifications that define the output format for display of each item.
3. Escape sequence characters such as \n, \t, and \b.
 The control string indicates how many arguments follow and what their
types are.
 The arguments arg1,arg2, …., argn are the variables whose values are
formatted and printed according to the specifications of the control string.
 The arguments should match with number, order and type with the format
specifications.

Output of Integer Numbers


The format specification for printing an integer number is
%w d
where w specifies the minimum field width for the output. However, if a number
is greater than the specified field width, it will be printed in full, overriding the
minimum specification. d specifies that the value to be printed is an integer. The
number is written right-justified in the given field width. Leading blanks will appear
as necessary. The following examples illustrate the output of the number 9876
under different formats
Format Output
9 8 7 6
printf(“%d”,9876) 9 8 7 6

9 8 7 6
printf(“%6d”,9876) 9 8 7 6

printf(“%2d”,9876) 9 8 7 6
printf(“%-6d”,9876) 9 8 7 6
printf(“%06d”,9876) 0 0 9 8 7 6

It is possible to force the printing to be left - justified by placing a minus sign


directly after the %d character, as shown in the fourth example above. It is also
24

possible to pad with zeros the leading blanks by placing a 0 (zero) before the field
width specifier as shown in the last item above. The minus (-) and zero (0) are
known as flags.

Output of Real Numbers


The output of a real number may be displayed in decimal notation using the
following format specification:
%w.p f
The integer w indicates the minimum number of positions that are to be used for
the display of the value and the integer p indicates the number of digits to be
displayed after the decimal point (precision). The value, when displayed, is
rounded to p decimal places and printed right-justified in the field of w columns.
Leading blanks and trailing zeros will appear as necessary. The default precision is
6 decimal places. The negative numbers will be printed with the minus sign.
We can also display a real number in exponential notation by using the
specification
%w.p e
Padding the leading blanks with zeros and printing with left-justification are also
possible by using flags 0 or - before the field width specifier w.
The following examples illustrate the output of the number y = 98.7654 under
different format specifications
Format Output
printf(“%7.4f”,y) 9 8 . 7 6 5 4
98.77
printf(“%7.2f”,y)
printf(“%-7.2f”,y) 9 8 . 7 7
98.7654
printf(“%f”,y)
printf(“%10.2e”,y) 9 . 8 8 e + 0 1
-9.8765e+01
printf(“%11.4e”,-y)
printf(“%-10.2e”,y) 9 . 8 8 e + 0 1
printf(“%e”,y) 9 . 8 7 6 5 4 0 e + 0 1
25

Printing of a Single Character


A single character can be displayed in a desired position using the format
%wc
The character will be displayed right-justified in the field of w columns. We can
make the display left-justified by placing a minus sign before the integer w. the
default value of w is 1.
Printing of Strings
The format specification for outputting strings is similar to that of real numbers. It
is of the form:
%w.ps
Where w specifies the field width for display and p instructs that only the first p
characters of the string are to be displayed. The display is right- justified.
Mixed Data Output
It is permitted to mix data types in one printf statement.
Example:
printf(“%d %f %s %c”, &count, &amount, name, &code);
is valid. printf uses control string to decide how many variables to be printed and
what their types are. Therefore, the format specifications should match the
variables in number, order and type. If there are not enough variables or if they
are of the wrong type, the output results will be incorrect.

You might also like