You are on page 1of 56

C – Language

C is a programming language developed at AT&T’s Bell laboratories of USA IN 1972. It was designed
and written by Dennis Ritchie in the late seventies. C began to replace the most familiar languages of
that time like PL/I, Algol etc., No one pushed C, thus without any advertisement C ‘s revolution spread
and its post of users grew. C stands between the ages; since it was designed have both a relatively
good programming efficiency and relatively good machine efficiency. Most I using operating was
loaded almost entirely in C. So “C” is said to be neither high level nor low level but it is said to be
middle level.
Development of “C”
At one stage people started thinking that instead of learning and using so many languages either for
a different purpose, why not use only the language which can program all; possible applications for
their purpose an International Committee was setup is develop a language, the committee came out
with a language ALGOL 60. It never became popular because it is too abstract, and too general. To
overcome these disadvantages a new language called CPL (Combined Programming Language) was
developed it also turned out to be so big having so many features and it was hard to learn and it is
difficult to implement. A new language was developed called BCPL (Basic Combined Programming
Language) developed by martin Richards but it was also failed because it was too less powerful and
too specific. At this juncture a language called B was written, like BCPL be to turn out to be to specific.
Dennis Ritchie inherited the features of B and BCPL added some of his own and developed a new
language called C. C’s compactness and coherence is mainly due to the fact i.e. one man language
other examples of one man languages are LISP, PASCAL, and APL.
Features of C:
 C is general purpose language
 It has a high degree of portability
 C is a block structure programming
 C is a function oriented language and it has rich set of functions, all the operations are
carried out through functions, which are placed in header files.
 C can be used for both scientific and business applications.
 All additional tasks such as graphical, mathematical, I/O operations are carried out
through library function, which are placed in separate header files.
 C can be used for both system programming and application programming.
 C permits to manipulate with bits, bytes and a memory addresses.
 C is a case sensitive language.
 The user can write a new functions those functions are called user defined functions.
 C supports recursion.
 Call-by-value and call-by-reference are used for parameter passing.
 C variables can be defined with scope such as auto, static, external, and register.
 C supports dynamic memory allocations using the functions Malloc, Calloc which are
place in header file stdlib.h.
 Preprocessor directives are available in C
 C is not a strongly type language that means mixing of data types doesn’t show any error.

pg. 1
 C is versatile language which can be used in the development of scanners, operating
systems, printers etc.,

Disadvantages:
 C cannot be understood easily until the user has theoretical depth or it is thought by C
professional.

Structure of C program

Documentation Section

Link Section

Definition Section

Global Section

Main ()
{
Declaration Part;
Executable Part;
}

Sub-Program Section

Function1 ()
{

}
Function2 ()
{

Documentation Section:
This section consists of set of comments, which tells name of the program, compilation time, date of
written etc. Which helps the user to identify the program.
Link Section:
It provides instructions to the compiler to link functions from system library.
Definition Section:
The Definition Section defines symbolic constants, which are invoked at the time of compilation.
Global Section:
The variables, which are declared in the section, are called as Global Variables and these variables
can be used through out the program.
Main Function:
Every C program must have only one main, which consists of two parts they are
 Declaration part.
 Executable part.

pg. 2
Variables, which are used in Executable part, should be declared in the Declaration part. These two
are enclosed between opening brace and ending brace. The compilation or execution starts at
opening brace and ends at ending brace. Closing brace of the main function is a logical end of the
program. All the statements in executable part and declaration part should end with semicolon (;).
Subprogram Section: This section contains all the user-defined functions, which are defined by the
user, and these functions may be placed after the main, which may appear in any order.
Main function is compulsory the user may exclude all other sections if required he can use.
Character Set:
A program is designed with the help of characters. C has its own vocabulary and grammar; it is
divided into two sets they are:
 Source Characters.
 Execution Characters.
Source Characters:
Using these characters programs is written they are divided into three. They are
 Alphabets A - Z to a - z.
 Digits 0-9
 Special symbols /, {,}, [,]…. Etc.,
Execution Characters:
The effect of these characters is felt at the time of execution. They are also called as escape
sequences or Back Slash characters.

Character Meaning Purpose


“\a” Audible Sound It makes alarm sound
It takes the cursor to the starting
“\n” New Line
position of the next new line.
It takes the cursor to the one space
“\b” Back Space
backward.
It takes the cursor to the starting
“\r” Carriage Return
position of the same line.
It takes the cursor to the horizontal
“\t” Horizontal Tab
tab space.
It takes the cursor to the vertical tab
“\v” Vertical Tab
space.
“\0” Null Character It is used for string operation.

Identifier
Identifier refers to the name of the variable, function and arrays. These are defined by user, which
consists of a sequence of letters and digits, with an alphabet as first character. Meaning is not
predefined; the user gives meaning.
Examples:
maximum, minimum etc.,
Keyword
Keywords have predefined meaning, which are given by the system. Keywords serve as basic
building blocks for program. User cannot change the meaning.
Examples:
main, for, int, float, char, while, if, if-else etc.,

pg. 3
Variable:
It is a memory location in which a value can be stored and this value may be changed at time of
execution.
Rules to define a variable:
 First character must be a alphabet and the remaining characters may letters
or digits.
 Variable should not be keyword.
 No special symbols are allowed expect underscore (_) for defining a meaning
variable if the variable length is too long. For example totalmaximum can be
declared as tot_max.
 Uppercase and lowercase are significant that is the variable avg is not same
as AVG, or Avg.
 More than one variable are to be separated by commas.

76
Memory Location
78090
Address Value at that address.
Data Types in C:
Any variable used in the program must be declared with appropriate data type before using it in any
statement and the data type declaration statement is usually written at the beginning of the C
program. This declaration of the variable performs various functions. They are:

 It introduces a new identifier that is the name of the variable into the program.
 It identifies the data type of the variable, which directs the ‘C’ compiler how to
store the variable’s value, whether it can have fractional component or
whether it is allowed to be negative as well as positive.
 It defines the variable meaning that the appropriate amount of main memory
is allocated to the value or variable.
 It may also initialize a variable – assign a meaningful value.

Syntax:
<datatype> var1, var2,…., varn;
or
<datatype> var1 = <value>, var2 = <value>,……, varn = <value>;
C has rich set of data types. It is classified into four data types they are:
 Fundamental Data Type.
 Derived Data Type.
 User Defined Data Type.
 Empty Set Data Type.
Fundamental Data Types:
It is most important data types in C, by using these data types, the user will the programs and it is the
building stone to all other data types. It is broadly classified into four. They are:
pg. 4
 int (Integer)
 float (Real Values)
 char (Character)
 double (Same as Float)
Integer Data type:
In this type only integer values can be accepted and at the time compilation, variable is allocated with
2 bytes of memory location.
Syntax:
int var1, var2,…..,varn;
Example:
int max, min, tot;
From above example max, min and tot are three valid variables of type integer and get 2 bytes of
memory location each.
Floating Point Data Type:
In this type integer and real values can be accepted and at the time compilation, variable is allocated
with 4 bytes of memory location.
Syntax:
float var1, var2,…..,varn;
Example:
float max, min, tot;
From above example max, min and tot are three valid variables of type integer and get 4 bytes of
memory location each.
Character Data Type:
In this type only character values can be accepted and at the time compilation, variable is allocated
with 1 byte of memory location.
Syntax:
char var1, var2,…..,varn;
Example:
char max, min, tot;
From above example max, min and tot are three valid variables of type integer and get 1 byte of
memory location each.
Double Precision Data Type:
In this only integer and real values can be accepted and at the time compilation, variable is allocated
with 8 bytes of memory location.
Syntax:
double var1, var2,…..,varn;
Example:
double max, min, tot;
From above example max, min and tot are three valid variables of type integer and get 8 bytes of
memory location each.

pg. 5
Qualifiers:
User has flexibility to increase or decrease the size memory locations as per the application
requirement. They are classified into four qualifiers. They are:
 short
 long
 signed
 unsigned
General Syntax for Qualifier is:
<qualifier> <data type> var1, var2,….,varn;
Short:
This qualifier decreases the size of memory. It can be used with integer.
Example:
short int max, min, tot;
From above example max, min and tot are three valid C variables, which is of type short integer,
which gets 1 byte of memory location each.
Long:
This qualifier increases the size of the memory. It can be used with integer and double.
Example:
long int max, min, tot;
From above example max, min and tot are three valid C variables, which is of type long integer, which
gets 4 bytes of memory location each.
Example:
long double max, min, tot;
From above example max, min and tot are three valid C variables, which is of type long double, which
gets 10 bytes of memory location each.
Unsigned:
This qualifier only takes positive values and it can apply with integer and character. In this memory will
increase or decrease but ranges will differ. In early case the range integer is –32768 to 32767 and for
character the range –128 to 127.
Example:
unsigned int max, min, tot;
From above example max, min and tot are three valid C variables of type unsigned integer, which
takes only the positive values, and range becomes from 0 to 65535.
Example:
unsigned char max, min, tot;
From above example max, min and tot are three valid C variables of type unsigned integer, which
takes only the positive character values, and range becomes from 0 to 255.
Signed:
For any data type the qualifier signed is default.
Derived data types:

pg. 6
Data types, which are, derived form the fundamental data types, such data types are called derived
data types. There are divided into types. They are:
 Array.
 Structures & unions
 Pointers
Array:
It is collection of homogenous elements.
Example:
Int max[15];

Structures & unions:


It is collection heterogeneous elements.
Example:
struct employee union employee
{ {
int no; int no;
char name[30]; char name[30];
float bp; float bp;
}emp; }emp;
Pointer:
It is variable which stores the address of another variable.
Example:
int *p; where is a pointer which points to integer
User defined data types:
Data types, which are defined by the user, are called as user defined data types. There are classified
into two types. They are:
 typedef
 enumerated data type.
Syntax for the first one is:
typedef type identifier;
where type refers to an existing data type and identifier refers to the new name given to the data type.
The existing data may belong to any class of type.
Example:
typedef int marks;
typedef float avg;
here marks indicate int and avg indicates avg, they can be used to declare variables as shown below.
marks batch1, batch2;
avg st1, st2;
batch1 and batch2 are declared as int variables and st1, st2 are declared float. The main advantage
of typedef is that we can create meaningful data type names for increasing the readability of the
program.
enumerated data type:

pg. 7
Syntax:
enum identifier {value1, value2,……,value n};
the identifier is a user defined enumerated data type which can used to declare variable that can have
of the values enclosed within the braces (known as enumeration constants).
Example:
enum day {Monday, Tuesday,…, Sunday};
enum day st, en;
st = Monday
en = Friday;
The compiler automatically assigns integer digits beginning with 0 to all the enumeration constants.
However the automatic assignments can be overridden by assigning values explicitly to the
enumeration constants.
Example:
enum day {Monday = 1, Tuesday = 2, ….., Friday = 5 };
Operators in C
An operator is a symbol that tells the computer to perform certain mathematical or logical operations.
These are used in programs to manipulate data and variables.
Expression:
Combination of operators and operands is said to be an expression. It is evaluated from left to right
using the precedence of operators.
C operators are classified into 8 types. They are:
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
 Increment/Decrement Operators
 Conditional Operators
 Bit Wise Operators
 Type Casting
 Special Operators
Arithmetic Operators:
C provides all basic arithmetic operators. They are: +, -, *, / and %.
Arithmetic Expression:
Combination of arithmetic operators with operands is said be arithmetic expression. It is evaluated
from left to right using the precedence of operators. Precedence is given below for arithmetic
operators. They have two level of precedence.
 *, / And %.
 + And -.
If the expression has parentheses than the first parentheses are evaluated according to the
precedence levels and from left to right.
Example:
a = a + 10;
pg. 8
b = a + c ( 10 * c );

Relational Operators:
Using these operators, user can compare two quantities and take certain appropriate decision. C
supports six relational operators they are:
 <, >, >=, <=, !=, ==
Relational Expression:
Combination of relational operators with operands is said be relational expression.
Example:
exp1 > exp2
a>b
x + a > 10
Logical Operators:
By using these operators, user can test the condition of relational expression. The operators are
 && - and
 || - or
 ! - not
Logical Expression:
Combines two or more relational expression with logical operators is said to be logical expression or
compound relational expression.
Example:
(exp1 > exp2) && (exp3 > exp4)
(a > b ) && (a > c)
Assignment Operators:
By using this operator a value or the result of an expression can be assigned to a variable.
Assignment operator is classified into four types. They are:
 Simple assignment
 Declaration assignment
 Multiple assignment
 Shorthand assignment

Simple Assignment:
It is used to assign a value or the result of an expression to left hand side variable.
Syntax:
<variable> = value or <expression>;
Example:
max = 10;
x = a + 10;
y = x + a;
Declaration Assignment:

pg. 9
At the time of declaration certain values are assigned to the variables or variables are initialized with
values such type of assignment is said to be declaration assignment.
Syntax:
<datatype> <variable> = value;
Example:
int max = 10;
Multiple Assignments:
More than one variable is assigned with value or expression, such type of expression is said to be
multiple assignment.
Syntax:
<Variable> = <variable> = value or <expression>
Example:
max = min = 10;
x = y = z + 10;
Shorthand Assignment:
Syntax:
<Variable> <operator> = value or <expression>
Example:
Count + = 1;
The use of shorthand assignment has three advantages:
 What appears on the left hand side need not be repeated and therefore it
becomes easier to write.
 The statement is more concise and easier to read.
 The statement is more efficient.
Increment \ Decrement Operators:
C has two useful operators not found in older languages. The operators are Increment \ Decrement
operators. ++ is said to be increment operator and -- is said to be decrement operator. The operator +
+ adds 1 to the operand and the operator -- will decrement the value by 1. It has two forms one is pre
increment \ pre decrement and post increment \ post decrement. These operators are mostly used in
looping structures.
Post Increment \ Post Decrement:
Operators after operand is said to be post increment or post decrement. It takes the following form.
<Variable>++ or <variable>--
a++ or a--
Pre Increment \ Pre Decrement:
Operators before the operand is said to be pre increment \ pre decrement. It takes the following form.
++<variable> or -- <variable>
++a or --a
a++ and ++a works same as when they form simple statements independently. They behave
differently when they are used in expressions. Consider the following examples.
Example:
Y=5;

pg. 10
A=y++;
From above example the value of y is assigned to a and then y is incremented by 1. The outputs are y
= 6 and a = 5.
Example:
Y=5;
A=++y;
From above example first the value of y is incremented and that value is assigned to a. The outputs
are y = 6 and a = 6
A prefix operator first adds 1 to the operand and then the result is assigned to the left hand side
variable on the other hand a postfix operator first assigns value to the left side variable and then
increments operand by one.
Conditional Operator (or) Ternary Operator:
It is used for test the condition using the conditional operators. It is also said to be ternary operator. It
consists of “? :” using these two operators an conditional expression is evaluated. The syntax as
follows:
Syntax:
exp1 ? exp2 : exp3;
where exp1, exp2 and exp3 are valid c expressions. First expression1 is evaluated. If the exp1 is
found to be true then the exp2 is evaluated and if the exp1 is found to be false then exp3 is evaluated.
Note that only one of the expressions is evaluated.
Example:
x = (a > b) ? a : b;
Bit wise Operators:
By using these operators, C can manipulate the data at bit level. These operators are used for testing
bits and shifting the bits from left to right or right to left. These operators are not be applied to float and
double.
Bit Wise Operators
Operators Meaning
& Bit wise AND
| Bit wise OR
<< Bit wise LEFT SHIFT
>> Bit wise RIGHT SHIFT
^ Bit wise exclusive OR
~ Bit wise Complement
Type Casting:
It converts from one data type form to other data type form at the time execution.
Syntax:
(data type) <variable>;
Example:
int a;
(float) a;
At the compilation a is of type integer and but at time of execution the a is converted to the float.
Special operators:
It supports some special operators they are:
 comma operator

pg. 11
 sizeof operator
 pointer operator (* and &)
 member selection operator (. And ->)
Comma Operator:
The comma operator can be used to link the related expression together. It is also evaluated from left
to right.
Example:
a = (x = 10, y = 5, x + y);
first value 10 is assigned to x, value 5 is assigned to y and finally 15 is assigned to a.

sizeof() Operator:
this operator is compile time operator and when used it returns the numbers bytes occupied by the
variable or that particular data type.
Syntax:
sizeof(datatype);
Or
sizeof(variable);
Example:
1.sizeof(int);

2. float a;
sizeof(a);
From first example the it displays the size 2 bytes and from second example it displays 4 bytes.
Pointer Operators (* and &):
The first operator * is used for display or accept the value present at that address.
The second operator & is used to access the address of the location.
These two operators are for used with pointers.
Member Selection Operators ( . and ->)
These two operators are used with structures. Both are used selecting members, which are declared
with structure data type.

Input / Output functions


Reading, processing and writing data are the three important essential function of a computer
program. Unlike other high – level languages, C does not have any built in I/O statements as part of
its syntax. All I/O operations are carried through functions, which are kept in header file. These
functions are collectively called as the standard I/O library. These are also called as console I/O
functions. It is classified into two types. They are:
 Unformatted functions.
 Formatted functions.
Unformatted Functions:

pg. 12
There are several standard library functions available under this category- those, which can deal with
a single character and those, which can deal with a string of characters. Which does not have format
while accepting or displaying data.
Unformatted Input Functions:
getch(), getche(), and getchar() are three unformatted input functions. The three functions are used to
accept a single character.
getch():
It takes a single character and it will not echo on the screen.
Syntax:
<variable> = getch();
Example:
ch = getch();
getche():
It takes a single character and it will echo on the screen.
Syntax:
<variable> = getche();
Example:
ch = getche();
getchar();
it also works same as getch() and getche(). When this statement is encountered, the computer waits
until a key is pressed and then assigns first character to the variable.
Syntax:
<variable> = getchar();
Example:
char ch;
ch = getchar();

Unformatted Output Function:


putch() and putchar() are used display the single character. Syntax and example as show below:
Syntax:
putch(variable);
putchar(variable);
Example:
putch(ch);
putchar(ch);
Where ch is the character variable.
Formatted Input Function:
Formatted input refers to an input data that has been arranged in a particular format. By using this
function user can accept various data format like integer, real and character values. scanf() function is
used to accept data, which is given by the user. Syntax for scanf() is given below:
Syntax:
scanf(“”control string”, &arg1, &ar2,….,&argn);

pg. 13
scanf() as two parts one is control string which specifies the field format in which data is to be entered
and the other part is arguments which specify the address of locations where the data to be stored.
Control string contains field specifications, which direct the interpretation of input data. It may include
 Field specifications, consisting of the conversion character %, a data type
character and an optional number. Specifying the field width.
%wd
The percentage sign (%) indicates a conversion character, which is matched with the data type the
user, has declared. W is an integer number that specifies the field width of the number to be read.
Example:
scanf(“%d”, &I);
scanf(“%d %f %c”, &max, &basic, &gen);
scanf(“%d %f %c %s”, &max, &basic, &gen, name);
Points to remember while using scanf()
 All functions arguments, expect control string, must be pointers to variables.
 Format specifications contained in the control string should match the arguments
in order.
 Input data items must be separated by spaces and must match the variables
receiving the input in the same order.
 The reading will be terminated, when scanf encounters an “invalid mismatch” of
data or a character that is not valid for the value being read.
 When searching for a value, scanf ignores line boundaries and simple looks for
the next appropriate character.
 Any unread data items in a line will be considered as part of the data input line to
next scanf call.
 When the field width w is used, it should be large enough to contain the input
data size.
Formatted Output Function:
Like scanf, user can use printf to print the data int specified format. The syntax is as shown below.
Syntax:
printf(“control string”, arg1, arg2,…..,argn);
Control string consists of three types of items:
 Characters that will be printed on the screen as they appear.
 Format specifications that define output format for display of each item.
 Escape sequence characters such as \n, \t and \b.
The control string indicates how many arguments and the arguments are variables whose values are
to be printed according to the specifications of the control string.
%w.p <conversion character>
Where w is an integer number that specifies the total number of columns for the output value and p is
another integer number that indicates the number of digits to the right of the decimal point or number
of characters to be printed from the string. Both w and p are optional.
Examples:
printf(“Welcome to C”);

pg. 14
printf(“%d”, sum);
printf(“%d Is The sum of Two Numbers.”, sum);
printf(“Sum = %d”, sum);
printf(“%d %f %s %c”, no, basic, name, gen);
printf(“\n”);
printf(“Sum = %d \n Average = %f”, sum, avg);
scanf and printf uses the format codes which is given below in table:
Code Meaning
%c Read a single character
%d Read a decimal integer
%e Read a floating point value
%f Read a floating point value
%g Read a floating point value
%h Read a short integer
%i Read a decimal, hexadecimal or octal integer
%o Read an octal integer
%x Read an hexadecimal integer
%s Read a string
%u Read an unsigned decimal integer
%[..] Read a string of word(s)
gets() and puts():
These two functions are unformatted I/O functions. gets() receives a string from the keyboard. Scanf()
has some limitation while receiving string of characters. For example:
User want to store a “Welcome to C”. The given whole string will not be stored, because the moment
the blank is encountered, the scanf() assumes the end the string. To overcome this problem C gives a
function called gets() which can store whole string. Syntax is as shown below:
Syntax:
gets(variable);
Where variable is declared string of chars.
Example
gets(name);
puts():
This function is used output the string.
Syntax:
puts(variable);
Where variable is declared string of chars.
Example:
puts(name);
Control structures
Depending on the circumstances, certain statements are to repeated or depending on the conditions
certain statements have to be executed. C supports four different control structures. They are
 Unconditional control structure.
 Conditional control structure.
 Multiple conditional control structure
 Looping control structure or iterative statements
Unconditional Control Structure:

pg. 15
The flow of execution is transferred from one point to another in the program without checking any
condition such type of execution is said to unconditional jumping or unconditional control structure.
goto statement is used for unconditional control structure. Syntax as shown below:
Syntax:
goto label;
label specifies where control is to transferred. Label is valid variable name, and must be followed by
colon.
Example:
goto x;
-------
-------
x: printf(“%d”, avg);
------
-----
From above example the control is transferred to the label corresponding to x, which is
unconditionally.
If program has more number goto statements. The user cannot the read the program properly and it
becomes unstructured program. So the user has avoid the usage of goto statement in the program. it
has two types of jumps. They are
 Forward jump.
 Backward jump.
Syntax for Forward jump:
goto label;
----------;
----------;
label: statement;
----------;
----------;
Syntax for Backward jump:
---------;
---------;
label: statement;
---------;
---------;
goto label;
Backward jump becomes a infinite loop, because control is always transferred back to the label.
Conditional Control Structure:
The control is transferred from one point to another in the program depending on the condition. It also
said to be two way branching statements, because it has to execute either the statements after the
testing the condition. If statement is used for checking the conditions and depending on the test
condition either true statements or false statements are executed. It has four forms. They are:
 Simple if

pg. 16
 if – else
 Nested if
 elseif ladder
Simple if Statement:
Syntax:
if (expression)
{
block of statement(s);
}
statement-n;
The block of statement(s) may be a single or block statements to be executed. If the expression is
true, then the corresponding block statements will be executed, otherwise the statement-n is
executed. In simple-if a problem is there, that is even the condition is true the statement-n is executed
after the execution of block of statements.
Flow chart:
entry

true
Is Exp
?

false
Statement (s)

Statement - n

Example:
-----------;
-----------;
if (sex == ‘m’)
{
bp = bp + 100;
}
bp = bp + 200;
The if-else Statement:
Syntax:
if (expression)
{
block of statement(s);
}
else
{
block of statement(s);

pg. 17
}
statement-n;
if the expression is true then the true block of statements will be executed, otherwise false block of
statements are executed. In either case, either true-block or false-block will be executed, not both.
Flowchart:

true false
Is Exp
?

Statement (s) Statement (s)

Statement - n

Example:
if (max > min)
{
max = max + 10;
printf(“%d”, max);
}
else
{
min = min – 10;
printf(“%d”, min);
}
max = max + min;
From above example first condition is tested, depending on that condition if statements are executed.
If a found to be greatest than value of max is incremented by 10 and the value max is printed. If max
is not true than min is decremented by 10 and the value of min is printed.
Nesting of if – else Statement:
When a series of decisions are involved, then the user has use more than one if – else statement in
nested form as shown below:
Syntax:
if (expression1)
{
if (expression2)
{
block of statement1 (s);
}
else
{
block of statement2 (s);
pg. 18
}
}
else
{
block of statement3 (s);
}
statement – n;
From above syntax, if the expression1 is false, the block of statement3 (s) will be executed otherwise
the expression2 is evaluated if the expression2 is true, the block of statement1 (s) will be executed it
otherwise the block of statement2 (s) will be executed and then the control is transferred to the
statement-n.
Flowchart: Entry

False Is Exp1 ? True

False Is Exp2 ? True

Statement(s) Statement(s) Statement(s)

Statement - n

Example:
If ( a > b )
{
if ( a > c )
printf(“%d”, a);
else
printf(“%d”, c);
}
else
{
if ( c > b )
printf(“%d”, c);
else
printf(“%d”, d);
}
From above first condition fails, the control is transferred to else part, again condition is tested, if c
found be greatest than the value of c is printed, if d found to be greatest then the value of d is printed.

pg. 19
If the first condition found to be true then the corresponding second test is evaluated, if a is found to
be true than value of a printed otherwise the value of c is printed.
The else – if Ladder:
There is another way of putting ifs together when multi path decisions are involved. A multi path
decision is a chain of ifs in which the statement associated with each else is an if. The syntax as
shown below:
Syntax: if (expression 1)
block of statement 1 (s);
else if (expression 2)
block of statement 2 (s);
else if (expression 3)
block of statement 3 (s);
else if (expression n)
block of statement n (s);
else
default – statement (s);
statement – n;
The above construct is known as the else if ladder. The conditions are evaluated from the top
to downwards. As soon as the condition is found, the corresponding statements are executed and the
control is transferred to the statement – n that means skipping the rest of the ladder. When all the
conditions become false then the final else containing the default statement will be executed.
Flowchart: entry

Is Exp1
?

Statement (s) Is Exp2


?

Statement (s) Is Exp3


?

Statement (s) Is Exp4


?

Statement (s) Statement (s)

pg. 20
Statement -n
Example:
if (marks > 79)
grade = “Honors”;
else if (marks > 59)
grade = “First Division”;
else if (marks > 49)
grade = “Second Division”;
else if (marks > 39)
grade = “Third Division”;
else
grade = “Fail”;
printf(“%s”, grade);
Multi Conditional Control Structure:
The user can design a program using if statements to control the selection, the complexity of such a
program increase dramatically when the number of alternatives increases. The program becomes
difficult to read and follow. At times, it may confuse even the person who designed it. C has a built-in
multi way decision statement known as switch. The switch statement tests the value of a given
variable against a list of case values and when a match is found, a block of statements associated
with that case is executed. The syntax is show below:
Syntax:
switch(expression)
{
case value-1:
block-1;
break;
case value-2:
blcok-2;
break;
-----------
-----------
-----------
default:
default-block;
}
statement – n;
From above the expression is an integer or characters. Value-1, Value-2,…….. are constants or
constant expression and are know as case labels. Each of these values should be unique within a
switch statement, block-1, block-2…….. are statement lists and may contain zero or more statements.
There is no need to put braces around these blocks. Note that case labels end with a colon (:). The
break statement at the end of each block signals the end of a particular case and causes an exit from
the switch statement, transferring the control to the statement-n.

pg. 21
Flowchart:
Entry

Switch Expression

Value 1
Block -1

Value 2
Block -2

Default No match
Default
Block

Example:
Statement n
switch(code)
{
case 1:
printf(“One”);
break;
case 2:
printf(“Two”);
break;
case 3:
printf(“Three”);
pg. 22
break;
default:
printf(“The Code is Not Matched”);
}
printf(“Finished Switch”);

Looping Control Structures or Iterative Statements:


The versatility of the computer lies in its ability to perform a set of instructions repeatedly. This
involves reading some portion of the program either a specified number of times or until a particular
condition is being satisfied. This repetitive operation is done through a loop control structure. Any
control structure has four steps. They are:
 Setting and initialization of a counter.
 Testing for a specified condition for execution of the loop.
 Execution of the statements in the loop.
 Incrementing / decrementing the counter.
A program loop consists of two segments, one known as the body of the loop and the other known as
the control statement. The control statement tests certain conditions and then directs the repeated
execution of the statements contained in the body of the loop. Depending on the position of the
control statement in the loop, a control structure may be classified either as the entry-controlled or as
exit-controlled loop.

Entry-Controlled Loop:
The control conditions are tested before start of the loop execution. If the conditions are not satisfied,
then the body of loop will not be executed. For and while loop are entry-controlled loop.
Flowchart:

Entry

Is Exp? False

True

Block of Statements

for loop:
for loop is an entry-controlled loop that provides a more concise loop control structure.
Syntax:

pg. 23
for ( expression1; expression2; expression3)
{
body of the loop;
}
From above, expression1 means initialization, expression2 means testing and expression3 means
increment/decrement.
Example:
for ( i = 0; i < 10; i++)
{
printf(“%d\n”, i);
}
This for loop is executed for 10 times and the prints the digits 0 to 9. Semicolons must separate the
three sections enclosed within parentheses. Note that they is no semicolon at the end of the
expression that is increment section.
Different Forms of for loop:
The for loop in C has several capabilities that are not found in other loop constructs. User can added
more than three expressions as per program demands or he can exclude any of three expressions.
Example:
for ( i = 0, j = 0; i < n; i++)
for ( i = 0, j = 0; i < n; i++, j++)
for ( i = 0, j = 0; ( i < n && j < p); i++, j++)
i = 0;
for ( ; i < n; i++)
for (; ;) – infinity loop. This loop will be executed for infinity times, to come
from this loop, the user has to use break statement.
Nesting of for loop:
One for statement within another for statement is said to be nested for loop.

Example:
for ( i = 0; i < 10; i++)
{
---------------;
---------------;
for( j = 0; j < 10; j++)
{
----------------; Inner Outer
----------------; Loop Loop
}
pg. 24
------------;
------------;
}
The while Statement:
The simplest of all the looping structure in C is the while statement. It is also entry-controlled loop.
The body of the loop is executed until the test condition is found to be, if the test condition is found to
be false the control is transferred to statement next to the while loop. In this the condition is tested at
the first, depending on the tested condition the body of the loop is executed.
Syntax:
Initialization;
while (expression)
{
body of the loop;
increment / decrement;
}
Example:
i = 0;
while ( i < 10)
{
printf(“%d\n”, i);
i++;
}
The body of the loop is executed for 10 times starting from i = 0, 1, 2….9 each time the value of i is
printed and the value of i is incremented by 1. if the i value is 10 the loop is terminated.
Exit-Controlled Loop:
The control conditions are tested at the end of the loop execution. If the conditions are not satisfied,
then the body of loop will not be executed. In this case at least once body of the loop is executed even
though the condition is false. The user has to be more cautious while using exit-controlled loop. Do-
while is exit-controlled loop.
Flowchart:
Entry

Block of Statements

Is
False
Exp ?

True

The do-while Statement:


pg. 25
Do-while is exit-controlled loop, in this the condition is tested at last and the body of loop is executed
depending on the tested condition. The loop is executed at least once even the condition is found be
false.
Syntax:
initialization;
do
{
body of the loop;
increment / decrement;
} while (expression);
Example:
i = 0;
do
{
printf(“%d\n”, i);
i++;
} while (i < 10);
The body of the loop is executed for 10 times starting from i = 0, 1, 2….9 each time the value of i is
printed and the value of i is incremented by 1. if the i value is 10 the loop is terminated. If the value of i
= 10, then the value of i is printed before loop is terminated, that mean even condition is false the loop
is executed is at least once.
Jumps in Loops:
Loops perform a set of operations repeatedly until the control variable fails to satisfy the test-
condition. More often, the user come across situations where user want to jump out of a loop instantly,
without waiting to get back to the conditional test. When executing a loop it becomes desirable to skip
a part of the loop or to leave the loop as soon a certain condition occurs. C permits two statements.
They are: break and continue.
Break:
When keyword break is encountered inside a loop, the loop is immediately exited and the program
continues with the statement immediately following the loop. When the loops are nested, the break
would only exit from the loop containing it. That is the break will exit only a single loop. Break
statement can be used with if condition, within looping structures.
Syntax:
break;
Example:
for ( i = 2; i <= n / 2; i++)
{
if ( n % i == 0 )
{
flag = 1;
break;
}
}
pg. 26
The above example to find the given number is prime or not. If the number has a factor it comes out
the loop due break statement.
Continue:
When keyword continue is encountered inside the loop, causes the loop to be continued with the next
iteration after skipping any statements in between. Continue statement can be used with if condition,
within looping structures.

Syntax:
continue;
Example:
for ( i = 1; i <= n ; i++)
{
for ( j = 2; j <= n / 2; j++)
{
if ( i % j == 0 )
continue;
}
printf(“%d\n”, i);
}
The above example to display the prime numbers 1 to n. If the number has a factor it remaining part
of the loop is skipped and it goes for the next iteration due continue statement in the inner loop.
Arrays
Array is derived datatype. It is collection of homogenous elements of same data type. Or an array is a
group of related data items that share a common name. It is classified into three categories. They are
 One-Dimensional Array (1D).
 Two-Dimensional Array (2D).
 Multi-Dimensional Array (ND).
One-Dimensional Array (1D):
An array, which is having single subscript, is said to be one-dimensional array. Declaration is as
shown below:
Syntax:
<data type> <variable>[size];
From above syntax, the data type indicate normal fundamental data type, variable is valid c variable
and the most important is size, which indicates the number locations it has to allocate at time
complication depending on the data type.
Example:
int a[10];
float b[20];
char c[10];

pg. 27
double e[20];
From above example, variable ‘a’ gets 10 continuous locations and each location having 2 bytes in
size so the total array size would be 20 bytes. Variable ‘b’ gets 20 continuous locations and each
location having 4 bytes in size so the total array size would be 80 bytes. Variable ‘c’ gets 10
continuous locations and each location having 1 byte in size so the total array size would be 10 bytes.
Variable ‘e’ gets 20 continuous locations and each location having 8 bytes in size so the total array
size would be 160 bytes.
C performs no bounds checking and therefore, care should be exercised to ensure that the array
indices are within the declared limits.
Accessing Array Elements:
The array elements are accessed or can be stored inside the array by using the index or subscript.
Always the array subscript starts from 0 and ends at n – 1 terms. First element of array will be in zero
place of the array and second element will be in 1 st place of the array and so on. User has to be
cautious will accessing or storing into array.
Example:
a[4] = 20; the element 20 is placed in the 4th position of the array.
printf(“%d”, a[3]); the 3rd is displayed that means 4th element.
a[i] --> i is used for subscript which can accepts any no of elements and
display elements depending on the size.

Initialization of Arrays:
User can initialize the elements of arrays in the same way as the ordinary variables. Array can be
initialized in two formats one with size and other without size the formats are given below.
Syntax:
<data type> variable[size] = {value1, value2,…..,valuen};
<data type> variable[] = {value1, value2,…..,valuen};
Example:
int max[5] = {10, 20, 30, 40, 50};
int min[] = {10, 20, 30};
From first example, 5 values initialized to the array variable max and the values are placed at the
appropriate position. From second example min is array variable without any size at the time of
compilation, the system will allocate enough space for the initialized elements that the size would
three.
Example:
int max[5] = {10, 20, 30};
From this example only three elements will be initialized to the array and the remaining location of the
array will be initialized to zero automatically at the time of compilation.
Two-Dimensional Array (2D):
An array, which is having two subscripts, is said to be two-dimensional array. These type arrays are
mostly used with matrices problems. It consists of row and col. First subscript indicates row and
second subscript indicates col. Declaration is as shown below:
Syntax:
pg. 28
<data type> variable[rowsize][colsize];
Example:
int mat[5][5];
From above example, variable ‘a’ gets 25 continuous locations and each location having 2 bytes in
size so the total array size would be 50 bytes. The represent is as shown below:
Col-0 Col-1 Col-2 Col-3 Col-4
Row-0 [0][0] [0][1] [0][2] [0][3] [0][4]
Row-1 [1][0] [1][1] [1][2] [1][3] [1][4]
Row-2 [2][0] [2][1] [2][2] [2][3] [2][4]
Row-3 [3][0] [3][1] [3][2] [3][3] [3][4]
Row-4 [4][0] [4][1] [4][2] [4][3] [4][4]
Accessing Array Items:
Array items are accessed or displayed using two subscripts. For example:
Example:
int[3][3] = 20; the element is stored in 3rd row in 3rd column.
printf(“%d”, a[2][4]) the element is displayed from 2 nd row and 4th column.
a[iI][j] --> Using two subscripts the values are stored and displayed.
Initializing Two-Dimensional Arrays:
Like one-dimensional array, two-dimensional array can also be initialized. The following example is
shown below.
Example:
int a[3][3] = {1,2,3,4,5,6,7,8,9};
int a[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}};
int a[3][3] = {
{1,2,3},
{4,5,6},
{7,8,9}
}; ---> Any of the formats can be used for initializing the elements into
the array. Elements 1,2,3 are initializes in 1 st row, 4,5,6 are initialized
in 2nd row and the 7,8,9 are initialized in 3rd row.
int a[2][3] = { {1,1}, {2}}; ---> Elements 1,1 are initialized in 0 th row of 0th and 1st
column corresponding and the 2nd column will be automatically initialized to 0. element 2 is initialized
in 1st row of 0th column and the remaining columns will be initialized to 0’s and the last row is all
elements are initialized to 0’s.
Like one-dimensional arrays the two-dimensional array can initialize without defining the size. The
size is defined at the time of compilation as per elements initialized.
Example:
int a[][] = {{1,2}, {3,4}, {5,6}}; --> size is 3 rows and 2 columns
Multi-Dimensional Array:
An array, which is having more than two subscripts, is said to be multi-dimensional array. The
compiler determines the exact limit. The general format is as shown below:
Syntax:
<data type> variable[size][size][size]…..[size];
Example:
pg. 29
int max[4][5][12];
float table[6][6][6];

Strings
A string is an array of characters. Constants in string are defined in two ways they are:
 Character constant.
 String constant.
Character Constant:
Character enclosed in between single quote is said to character constant. For example:
Example:
ch = ‘a’;
String Constant:
Character or string enclosed in between double quotes is said to be string constant. For example:
Example:
ch = “A”;
String can also be declared and initialized like normal variables like an array. The syntax as shown
below and example:
Syntax:
char string-name[size]; --> size determines the number of characters in the
string
Example:
char name[10];
char place[10];
The compiler assigns a character string to a character array; it automatically supplies a null character
(‘\0’) at the end of the string. Character array can initialized same as normal array.
Example:
char city[6] = “Delhi”
char city[6] = {‘D’, ‘e’, ‘l’, ‘h’, ‘i’, ‘\0’};
char city[] = {‘D’, ‘e’, ‘l’, ‘h’, ‘i’, ‘\0’};
The user has to be cautious while initializing character, one space has to be left for null character,
other wise the user may result in error. The last example, the size of the array will be determined
automatically, based on the number of elements initialized.
String handling functions
Frequently used functions are predefined and precompiled into library files. Their prototype can be
form into header files. Library functions improve program design and reduce debugging and testing
time and they’re by reducing the amount of needed for the development of program. The use library
function increases the program readability, reduces complexity and simplifies the program job. A C is
function-oriented language and everything is dealt with functions. To handle the operations on strings
C supports separate string functions. Some of the functions are given below. They are:

pg. 30
strlen():
calculates and returns the length of the given string to the integer variable.
Syntax:
<variable> = strlen(str);
Where str and variable is C valid variable names and str is of type array of characters and the variable
is of type of integer. The function strlen returns the no of character of the string str, not counting null
character or terminating character.
Example:
 n = strlen(“HELLO”);
 n = strlen(str);
from example 1 the n will have 5 and from example 2 it depends on the no of characters given to the
variable str, which is of data type array of characters.
strcpy():
It copies one string into another string.
Syntax:
strcpy(str2, str1);
Where str and str1 are valid C variables of type array of characters and str1 is source string and str2
is destination string. This function copies the string str1 into the string str2 that means overwrites onto
the string str2 if any text is present in str2.
Example:
 strcpy(str, “PASS”):
 strcpy(str2, str1);
From example 1 the constant string “PASS” is copied onto the string str and from example 2 the value
of source string str1 is copied onto the destination string str2. Where str1 and str2 are valid ‘C’
variables of type array of characters.
strcat():
Means concatenation. Appends one string to another string.
Syntax:
strcat(str2, str1)
Where str and str1 are valid C variables of type array of characters and str1 is source string and str2
is destination string. This function appends string str1 to the end of the string str2 and the length of the
string str2 will be strlen(str1) + strlen(str2).
Example:
Char str[20] = “Hello”;
 strcat(str, “ World”);
 strcat(str2, str1);
From example 1 the constant string “ World” is joined or appended to the end of the string str and the
resultant string str will be “Hello World”. From example 2 the value of the source string str1 is
appended to end of the destination string str2 and the resultant string will be str2 + str1. Where str1
and str2 are valid ‘C’ variables of type array of characters.
strcmp():
Compares one string with another string.

pg. 31
Syntax:
<variable> = strcmp(str2, str1);
Where str1 and str2 are valid C variables of type array of characters and variable is of type integer.
The function returns an integer value after comparing each character of the string str1 with str2, the
comparison depends the ASCII codes of string and gives the difference of the two strings. If the return
value is < 0 then the string str1 < string str2, if return value is equal to 0 then string str1 = string str2
and if the return value is > 0 then the string str1 > string str2. At the time comparison the characters
are treated as unsigned character data type.
Example:
1. 2. 3.
char str1[7] = “Hello”; char str1[7] = “Hello”; char str1[7] =
“World”;
char str2[7] = “World”; char str2[7] = “Hello”; char str2[7] =
“Hello”;
int n; int n; int n;
n = strcmp(str1, str2); n = strcmp(str1, str2); n = strcmp(str1,
str2);
From above three examples str1, str2 and n are valid c variables.
From 1st example each character of str1 is compared with string str2 and the comparison leaves to n <
0 that means string str1 < string str2 or string str2 > string str1. From 2 nd example after comparison
between two strings the n value is equals to 0 that means the string str1 is equals to string str2. From
3rd example after comparison n gets the value > 0 that means the string str1 > string str2 or string str2
< string str1.

strlwr():
converts the string into lower case.
Syntax:
strlwr(str);
This function converts all the characters into lower case and keeps in the same string. Where str is
valid C variable name of type array of characters.
Example:
char str[7] = “HELLO”;
printf(“%s”, strlwr(str));
from above example string variable str is assigned a value “HELLO” and using the function strlwr
“HELLO” is converted into lower case and it is displayed by using printf function. The displayed string
is “hello”.
strupr():
converts the string into upper case.
Syntax:
strupr(str);
This function converts all the characters into upper case and keeps in the same string. Where str is
valid C variable name of type array of characters.
Example:
pg. 32
char str[7] = “hello”;
printf(“%s”, strupr(str));
from above example string variable str is assigned a value “hello” and using the function strupr “hello”
is converted into upper case and it is displayed by using printf function. The displayed string is
“HELLO”.
strrev():
It reverses the given string.
Syntax:
strrev(str2, str1);
Where str1 and str2 are valid C variables of type array of characters, this function reverses the source
string str1 and the places int the destination string str2.
Example:
1. strrev(str1, “hello”);
2. strrev(str2, str1);
from 1 example hello is reversed that is olleh is placed in string str1. from 2 nd example str1 is
st

reversed and placed in the string str2.


strncpy():
copies a given number of characters from one string into another.
Syntax:
strncpy(str2, str1, n);
Where str1, str2 are valid C variables of type array of characters and n of type integer C variable,
which specifies the length of the string to be copied. The function copies maximum of no of characters
from source string str1 into destination string str2 and it will not place a null character into the copied
string.
Example:
1. strncpy(str2, “HELLO”, 4);
2. strncpy(str2, str1, n);
from 1 example up to the 4th character of the constant string is copied into the string str2, then the
st

result is “HELL”.
strncat():
Appends a portion of one string to another string.
Syntax:
strncat(str2, str1, n);
Where str1, str2 are valid C variables of type array of characters and n of type integer C variable, this
function concatenates maximum no of characters from source string str1 to destination string str2 and
appends NULL (‘\0’) character at the end of the string.
Example:
Char str[7] = “World”;
1. strncat(str1, “Hello”, 4);
2. strncat(str2, str1, n);
From 1 example the string str1 is appended up to the 4 th character of the constant string “Hello” and
st

a null character is added at the end of the string. The result after concatenation will be “WorldHell”.

pg. 33
From 2nd example maximum no of characters of the string str1 is appended to the str2 and the length
of str2 will be str2 = strlen(str2) + n.
strncmp():
This function compares a portion of one string with another string.
Syntax:
strncmp(str1, str2, n);
this function returns an integer value based from the result of comparing str1 (part of it) with str2 (part
of it). The returned values are:
*<0 str1 < str2
*>0 str1 > str2
* == 0 str1 == str2
this function compares unsigned characters but does not look beyond the length of n character, it
starts with 1st character in each string and continues for subsequent character until the character
differs or until it examines the length of character specified by the user.

Functions
Large programs for large “real world” applications require quite different techniques for their creations.
As programs grow in size and complexity it becomes more and more difficult to keep track of logic. So
programs are divide into separate modules called functions, with each function reflecting a well-
defined activity and of manageable proportions. The idea is to divide and conquer. The programs,
which are, divide into sub-programs or modules, such modules are known as functions.
Advantages of functions:
 Function makes the lengthy and complex program easy and in short from.
 Other programmer as per their requirements can use these functions.
 Function increases the speed of execution.
 Repeated statements can be grouped into functions.
 It easy to debug errors.
 Splitting the programs into separate functions makes the programs more
readable and maintainable.
C functions can be classified into two categories. They are: library function and user defined functions.
The main difference between these two is that library functions are not required to be written by the
user, where as the user-defined functions has be developed by the user. However, a user-defined
functions can later become a part of the C program library.
Function Definition:
C functions have same rules as variable name, with extra feature parentheses after name. The
parentheses may contain list of arguments and separated by commas. On invocation, the calling
program injects the values of these arguments into the function.

Syntax:
<data type> function (arguments)
{
declaration part;

pg. 34
executable part;
}
Example:
int max( int a, int b) int max( a, b)
{ int a, b;
statements; or {
} statements;
}

Flow of Function as Shown Below:


main()
{ Return Type
void function(); Function Declaration.
------------------;
function(); Calling Function
}
void function() Called Function
{
---------------------------;
---------------------------;
return();
}
Function declaration is also called as prototype
The function declaration specifies the following information:
 The name of the function
 The type of the value returned (default is integer).
 The number and type arguments that must be supplied to call the function.
Arguments are also known as parameters, they are of two types: actual parameters and formal
parameters. Actual parameters are those parameters by which the function is invoked and the formal
or dummy parameters will receive the values. These two parameters are used for communication
purpose between the calling and the called function. The following condition must be satisfied for a
function call.
 The number of arguments in the function call and function declaratory must be
the same.
 The datatype must be matched between actual parameters and formal
parameters.
 The order should be same.
C provides two mechanism to pass arguments to a function. They are call-by-value and call-by-
reference or address.
Call-by-Value:

pg. 35
In this the actual and formal parameters gets different memory locations. Whatever modification done
in formal parameters will effect the actual parameters, because both of them get different memory
locations. It has only one-way communication.
Example:
main()
{
int a = 10 , b = 10;
clrscr();
printf("Before Calling The Function Test\n");
printf("A = %d and B = %d\n", a, b);
test(a, b)
printf("After Calling The Function Test\n");
printf("A = %d and B = %d", a, b);
getch();
}
test(int a, int b)
{
a = a * 10;
b = b * 10;
printf("In The Function The Values are .\n");
printf("A = %d and B = %d\n", a, b);
}

After execution of this program the output are shown below:


Output:
Before Calling The Function Test
A = 10 and B = 10
In The Function The Values are .
A = 100 and B = 100
After Calling The Function Test
A = 10 and B = 10
Call-by-Reference:
In this the actual and formal parameters gets the same memory locations. Whatever modifications are
done the effect will be felt to actual parameters. In this the value will not be passed but the address of
the variable is passed to formal parameter. It has two-way communication.
Example:
main()
{
int a = 10 , b = 10;
clrscr();
printf("Before Calling The Function Test\n");
pg. 36
printf("A = %d and B = %d\n", a, b);
test(&a, &b);
printf("After Calling The Function Test\n");
printf("A = %d and B = %d", a, b);
getch();
}
test(int *a, int *b)
{
*a = *a * 10;
*b = *b * 10;
printf("In The Function The Values are .\n");
printf("A = %d and B = %d\n", *a, *b);
}
After execution of this program the output are shown below:
Output:
Before Calling The Function Test
A = 10 and B = 10
In The Function The Values are .
A = 100 and B = 100
After Calling The Function Test
A = 100 and B = 100
Categories of Function:
Depending on arguments and return value the function is classified in to three categories: they are
 Functions with no arguments and no return values.
 Function with arguments and no return values.
 Function with arguments and return values.
No Arguments and No Return Value:
When a function has no arguments, it does not receive any data from the calling function and also it
does not return value. So there is no data transfer between calling function and called function.
Flow is given below:
function1() function2()
{ {
-------------; No Input --------------;
function2(); No Output --------------;
-------------; return;
} }

With Arguments and No Return Value:


The main function has no control over way the functions receive input data. The calling function can
the read data from the terminal and pass it on to the called function. This approach seems too wiser
because the calling function can check for the validity of data. The nature of data communication

pg. 37
between the calling function and the called function with arguments but no return no value is shown
below:
function1() function2( int a, int b)
{ {
int a, b; With Arguments -------------;
-------------; --------------;
function2(a, b); No Return Value --------------;
-------------; return;
} }
With Arguments and With Return Value:
The calling function can the read data from the terminal and pass it on to the called function and the
calculated data is passed on to the calling function as a return value. A self-contained and
independent function should behave like a black box that receives a predefined form of input and
outputs desired values. Such functions will have two-way data communications as shown below:
function1() function2( int a, int b)
{ {
int a, b; With Arguments -------------;
-------------; --------------;
function2(a, b); With return value --------------;
-------------; return(c);
} }
Recursion:
When a called function in turn calls another function a process of “chaining” occurs. Recursion is a
special case of this process, where function calls itself. Whenever function is called recursively, it has
to satisfy two conditions. They are:
 It must have base criteria.
 It should be nearer to the base criteria when function is called.
If any of the condition is not met it will become infinity loop.
Recursive functions can be effectively used to solve problems where the solution is expressed in
terms of successively applying the same solution to subsets of the problem. The program must have
‘if’ statement somewhere to force the function to return without the recursive call being executed.
Otherwise, the function will never return.
The Scope and Lifetime of Variables in Functions or Storage Classes:
Every variable in a program has some memory associated with it. Memory for variables is allocated
and released at different points in the program. The storage classes determine the lifetime of the
storage associated with the variables. Some variables execute in the function program locally, but
other execute globally. The period of time during which memory is associated with a variable is called
the extent of the variable. The region of source code over which the declaration of an variable is
called the scope of variable. The variables are classified into two. They are:
 Local Variables.
 Global Variables.
Local Variables:

pg. 38
The variables, which are declared in the function and their visibility, are restricted to the function in
which they are declared such variables are called local variables.
Global Variables:
Variables declared outside all the functions are called global variables and can be accessed by all the
functions. Such variables are called global variables.
Besides these two, a variable in C can have any one of the following four storage classes, they are:
 Automatic storage class.
 Static storage class.
 External storage class.
 Register storage class.
Automatic Storage Class:
All variables declared with in a function are auto by default. These are created when the block is
entered into and destroyed when it is exited. These variables can be accessed only within the
function. These will not retain the values, after the block. One important feature of automatic variable
is that their value cannot be changed accidentally.
Example:
main()
{
int a = 1000;
clrscr();
function2();
printf("A = %d ", a);
getch();
}
function1() function2()
{ {
int a = 10; int a = 100;
printf("A = %d ", a); function1();
} printf("A = %d ", a);
}
Outputs:
A = 10 A = 100 A = 1000
From above the variable A is initialized with different values in three functions that after exited from the
block the value variable is not retained.
Static Storage Class:
The word static in a generic manner refers to the notion of anything that is inserted to changes. If the
variable is declared as static, it will not die till program ends and the value of the variable will be
retained. Unlike auto the static variable have initial value to zero and does not have a garbage value.
The variable can be declared as static using the keyword static. A static variable may be an internal or
external.
Example:
main()

pg. 39
{
int i;
for( i = 0; i < 3; i++)
function();
getch();
}
function()
{
static int cou;
printf("Value = %d ", cou);
cou++;
}
Outputs: Value = 0 Value = 1 Value = 2
At the first the value of static variable cou is initialized to zero and that is displayed, the value is
incremented and that value persists, for the second call the value present in the variable cou is
displayed as 1 and again the value is incremented by 1, and for the third call the value is displayed as
2. For each call the value persists.
External Storage Class:
Variables that are both active and alive throughout the entire program are known as external
variables. They are also known as global variables. External variables are declared outside the
function main. The variables are declared using the keyword extern.
Example:
main()
{
extern int i;
i = i + 1;
printf("I = %d ", i);
function();
printf("I = %d ", i);
}
int i = 10;
function()
{
i = i + 1;
}
The variable I is declared outside the main function it can accessed only with function extern before
the variable, after execution of the program the outputs are I = 11 and I = 12.
Register Storage Class:
C allows the use of registers in variable declaration. Such variables are called register variables and
are stored in the register of the microprocessor. Limited variables are declared as registers and if
more variables are declared they are treated as auto variables. These variables are accessed much
quickly than normal variables as they reside in the register of microprocessor. Most of the compilers
allow only int and char variables to be placed in the register. Since a register access is much faster
pg. 40
than a memory access, keeping the frequently accessed variables in the register will lead to faster
execution of programs. For example loop control variables etc.,
register int count = 0;
Structures and Unions
Structures:
If the user wants to represent a collection of data items of different types using a single name, then
user cannot use array, C supports a constructed data type known as structure, which is method of
packing data of different types. Or it is collection of heterogeneous elements of different data types.
The concept of a structure is analogous to that of a ‘record’ in many other languages. Structures help
to organize complex data in a more meaningful way. The structure is defined with keyword struct.

Syntax:
struct <tag_name> struct <tag_name>
{ {
<data type> member1; <Or> <data type> member1;
<data type> member2; <data type> member2;
….. …..
….. …..
}; } <var1>, <var2>,…..,<varn>;
Any of the two formats can be declared.
From above syntax, the member of a structure are not variables, they do not occupy any memory until
they are associated with structure variables.
Example:
struct employee struct employee
{ {
int empno; int empno;
char name[30]; char name[30];
float bp; float bp;
}; } emp;
First example can declare using the tag_name of the structure as shown, struct employee emp. 2 nd
example is directly given variable name at the end of the structure. In defining the structure the
following points are to noted.
 The template is terminated with a semicolon (;).
 While the entire declaration is considered as a statement, each member is
declared independently for its name and type in a separate statement inside the
template.
 The tag_name such as employee can be used to declare structure variables of its
type later in the program.
Normally, structure definition appears at the beginning of the program before any variables or function
are defined.

pg. 41
Accessing or Storing Structure Members:
Structure members are to accessed by the two special operators . they are:
 Dot (.)
 -> it used using the pointers
Dot (.) is used to link between the structure member and the variable. It also called as member
operator.
Example:
emp.empno = 10;
strcpy(emp.name, “spears”);
emp.bp = 10000.50;
Using scanf function we can stores the values through the keyboard.
scanf(“%d %s %d”, &emp.empno, emp.name, &emp.bp);
Using printf function values can also be printed on to screen.
printf(“%d %s %d”, emp.empno, emp.name, emp.bp);
Two structures can be compared like normal variables but the two structures should of same type and
must have same structure than only the comparison can be made.
Operation Meaning
emp1 = emp2 That means assign emp2 to emp1
emp1 == emp2 All the member of emp1 is compared with emp2. it returns 1 if they are equal 0 otherwise.
emp1 != emp2 Return 1 if all the members are not equal, 0 otherwise
Array of Structures:
User can declare array of structures like normal array declaration. And it is accessed using the
subscript. An of structures are stored inside the memory in the same ways as a multi-dimensional
array.
struct employee emp[100];
The above example defines an array called employee that consists of 100 elements, each element is
defined to be of the type struct emp.
Structures are classified into two types: They are:
 structure within structure
 referential structures.
Structure Within Structure:
Structures within a structure means nesting of structures. Nesting of structures is permitted in C.
Example: Struct employee
{
int empno;
struct
{
int date;
int month;
int year;
}bod;
char name[20];
float bp;

pg. 42
}emp;
The employee structure contains a member named bod which itself is a structure with three members.
The members contained in the inner structure namely date, month, and year can be accessed as
shown below:
emp.bod.date; emp.bod.month; emp.bod.year;
Referential Structures:
structure pointing to the same structure is said to be self-referential structure. Special operator (->) is
used to access the members of the referential structures. Most of them are used in the data
structures.
Example:
struct link
{
int no;
struct link *next;
}st;
Structures With Functions:
C supports the passing of structure values as arguments to functions. There are three methods by
which the values of a structure can be transferred from one function to another. The first method is to
pass each member of the structure as an actual argument of the function call. The actual arguments
are then treated independently like ordinary variable. The second method involves passing a copy of
entire structure to the called function. Any changes to structure members within the function are not
reflected in the original structure. The third employs a concept called pointer to pass the structure as
an argument. Any changes made to structure members within the function are reflected in the original
structure. The three methods are given below:
1st method call(st.name, st.no);
2nd method call(st);
rd
3 method call(&st);
Unions:
Union concept is same as structure. There is major distinction between them in terms of storage. In
structure each member has its own storage location, whereas all the members of union use the same
location, which implies union may contain many members of different types, it can handle only one
member one time. Like structures, a union can be declared using the keyword union as follows:
union employee
{
int empno;
char name;
float bp;
}emp;
The union contains three members, each with a different data type. Only one member can used at a
time. This is due to only one location is allocated for a union variable. The compiler allocates a piece
of storage that is large enough to hold the largest variable type in the union. From above example the
bp is the largest among the members. So all the three variables share the same address.

pg. 43
In effect a union creates a storage location that can be used by any one of its member at a time.
When a different member is assigned a new value, the new value supercedes the pervious member’s
value. Unions are mostly used with bit operations.

Pointers
A pointer contains the address of another variable. Or a pointer points indirectly to the value present
at that address. The advantages using pointers are listed below:
 A pointer enables us to access a variable that is defined outside the function.
 Pointers are more efficient in handling the data.
 Pointers reduce the length and complexity of a program.
 They increase the execution speed.
 The use of a pointer array to character strings result in saving data storage space
in memory.
Declaring and Initializing Pointers:
Like normal variables pointer also has same rules, but the variables are declared as pointers before
the user use them.
Syntax:
<data type> * <variable>;
From above syntax the following points:
 The asterisk (*) tells that the variable is a pointer variable.
 Variable needs a memory location.
 Variable points to a variable of type data type.
Example:
int *b; ---- The variable b is a pointer variable which points to integer data
type.
Once a pointer variable has been declared, it can be made to point to a
variable using an assignment operator.
Example:
int a = 10;
int *b;
b = &a; now b contains the address of the a, which indirectly points to the
value present in the variable a.

a 10
7896

b 7896

9078

Accessing a Pointer Variable:


A pointer has been assigned the address of a variable; by using indirection operator (*) that pointer
variable can be accessed, which is unary operator.
Example:

pg. 44
int a = 10, *b;
b = &a;
printf(“%d”, *b);
The first line declares a as an integer variable and b as a pointer variable pointing to an integer. The
second line assigns the address of a to the pointer variable b. the third line prints the value of a on to
screen, because the b value is the address of a. * is also said to be “value at address”.

Dynamic Memory Allocation


Most often, the user face situations in programming where the data is dynamic in nature, then the
user cannot use arrays because it has drawbacks. They are
 The array size is defined. And it is defined at compile time.
 At the run time, user added new location. For example if the array size is 100,
user as to added 101 record, he cannot added because the size is defined to 100
only.
 By using arrays, there wastage in memory. For example if the array size is 100,
only user uses only 10 locations and the remaining 90 locations are wasted.
So to overcome these problems C supports a feature called dynamic memory allocations. User has
flexibility to create or to destroy the memory whenever he wishes. Dynamic memory allocations
means creating the memory at the runtime not like the data type, which is created at the time
compilation. To allocate memory dynamically C uses four-library functions, which are called as
“memory management functions” and must be used with header file “stdlib.h”.
Function Meaning
Allocates requested size of bytes and returns a pointer to the first bye of the allocated
malloc()
space.
Allocates space for an array of elements, initializes them to zero and then returns a pointer
calloc()
to the memory.
free() Frees previously allocated space.
realloc() Modifies the size of previously allocated space.
Allocating Memory:
To allocate the memory c uses two functions. They are:
 malloc()
 calloc()
malloc():
A block of memory is allocated at runtime of specified size.
Syntax:
ptr_var = (cast type *)malloc(byte_size);
Example:
max = (int *)malloc(20); this statement allocates 20 bytes of spaces for the
pointer max of type int.

max

Address of
byte

20 bytes of space
pg. 45
max = (int *)malloc(100 * sizeof(int)); this statement allocates “100 times the
size of int” bytes and the address of the first byte of the memory allocated is
assigned to the pointer max of type int.
The space allocated dynamically has no name and therefore it contents can be accessed only through
pointer. A complex data type can also be allocated such as structures as shown below.
emp_ptr = (emp *)malloc(sizeof(emp));
where emp is a pointer of type struct employee.
calloc():
it also allocates the memory at runtime, but allocates multiple blocks of storage, each of same size
and then initializes all of them to zero.
Syntax:
ptr_var = (cast type *)calloc(n, element_size); this statement allocates
contiguous space for n blocks, each of size element-size bytes and all bytes
are initialized to zero. If there is not enough space a NULL pointer is returned.
Example:
emp_ptr = (struct employee *)calloc(10, sizeof(struct employee));
or
emp_ptr = (struct employee *)calloc(n, sizeof(struct employee)); where n is
size.
Releasing the Used Space:
User can release the space when it is not require. To release the memory a free() function is used.
Syntax:
free(ptr_var);
Example:
free(emp_ptr); emp_ptr is pointer to a memory block that, is created by
malloc() or calloc() and it is freed by the function free.
Altering the Size of Memory:
The size of memory is increased or decreased by using the function realloc() which is also called as “
“reallocation of memory”
Syntax:
ptr_var = (cast type *)realloc(ptr_var, new-size);
This function allocates a new memory space of size new-size to the pointer variable ptr_var and
returns a pointer to the first byte of the new memory block. The new-size may smaller or larger. If it is
not able to find additional space in the came region, it will create the same in an entirely new region
and move the contents of the old block into the new block. The function guarantees that the old data
will remain intact. If the function is unsuccessful in locating additional space, tit returns a NULL pointer
and the original block is freed(lost), so the user has to be cautious while using realloc() function.
Files
The functions such as scanf and printf are console functions, which always use the terminal as the
target place. This works fine as long as the data is small. The console oriented I/O operations pose
two major problems.

pg. 46
 It becomes cumbersome and time consuming to handle large volumes of data
through terminals.
 The entire data is lost when either the program is terminated or the computer is
turned off.
It is therefore necessary to have a more flexible approach where data can be stored on the disks and
read whenever necessary, without destroying data. C uses a file concept to overcome above two
problems. A file is collection of records and it is stored on the disk. The basic file operation are listed
below. They are:
 Naming a file.
 Opening a file.
 Reading data from a file.
 Writing data to a file
 Closing a file.
Defining a File:
The file must and should be declared as type FILE before it is used.
Syntax:
FILE *<variable>;
Example:
FILE *fp; the variable fp is a pointer to the data type “FILE” which points to
starting record of the file.
Opening a File:
Syntax:
<variable> = fopen(“filename”, “mode”);
The variable is valid C file pointer variable, fopen consists of two parts one is filename which is string
of characters which is valid filename and other one specify the modes which are listed below. They
are:
 r – open the file for reading.
 w – open the file for writing. A file with specified name is created if the file does
not exist. The contents are deleted if the file already exists.
 a – open the file for appending data to it (adding). The file is opened with current
contents safe. A file with specified name is created if the file does not exist.
 r+ - the existing file is opened for both reading and writing.
 w+ - same as w but it used for reading and writing.
 a+ - same as a but it is used for reading and writing.
Both the filename and modes are specified as strings. They should be enclosed in double quotes.
Example:
fp = fopen(“emp.dat”, “r”); the file “emp.dat” is opened in read mode.
fp = fopen(“emp.dat”, “w”); the file “emp.dat” is opened in write mode. If the
file is not present a new file is created with specified name and if it is present
the contents are erased.

pg. 47
fp = fopen(“emp.dat”, “a”); the file is “emp.dat” is opened in append mode. If
the file is present, then the file pointer fp is assigned to the last record. If not
a new file is created with the specified name.
if the file is not opened or cannot be created a NULL is returned to the file pointer.
Closing a File:
A file must be closed as soon as all operations on it have been completed. It also prevents any
accidental misuse of the file. To open the file in other mode, firstly the file, which is opened, should be
closed. fclose() is the function is used to close the file.
Syntax:
fclose(file pointer);
Example:
fclose(fp); where fp is the file pointer.
Input/Output Operations on files:
Input Functions:
getc():
This function gets a single character from the file. Syntax and example as shown below:
Syntax:
<variable> = getc(file pointer);
Example:
ch = getc(fp); where ch is character variable and fp is the file pointer. It reads
single character and is assigned to the character variable ch.
getw();
getw is integer oriented function. Which reads integer values from the file. Syntax and example as
shown below.
Syntax:
<variable> = getw(file pointer);
Example:
num = getw(fp); where num is integer variable and fp is the file pointer. It
reads the values from the file and assigns to the integer variable num.
fgetc():
This function is same as getc but it is function version of macro getc.
Syntax:
<variable> = fgetc(file pointer);
Example:
ch = fgetc(fp); where ch is character variable and fp is the file pointer. It reads
single character and is assigned to the character variable ch.
fscanf():
This function same as scanf, but fscanf works on files. It consists of three parts. They are:
 File pointer.
 Control string
 List of arguments.
Syntax:

pg. 48
fscanf(file pointer, “control string”, &arg1, &arg2,…..,&argn); this statements
reads the records until the end of file is reached.
Example:
fscanf(fp, “%d %s %c %f”, &no, name, &sex, &basic);
Output Functions:
putc():
This function writes the character on to the file. Syntax and example as shown below:
Syntax:
putc(variable, file pointer);
Example:
putc(ch, fp); where ch is a character variable, and fp is the file pointer. The
characters are written into the file.
putw():
This function is integer oriented functions and only writes integer values on to the file.
Syntax:
putw(variable, file pointer);
Example:
putw(num, fp); where num is a integer variable, and fp is the file pointer. The
integer values are written into the file.
fputc():
This function is same as getc but it is function version of macro putc.
Syntax:
fputc(variable, file pointer);
Example:
fputc(ch, fp); where ch is a character variable, and fp is the file pointer. The
characters are written into the file.
fprintf():
This function same as printf, but fprintf works on files. It consists of three parts. They are:
 File pointer.
 Control string
 List of arguments.
Syntax:
fprintf(file pointer, “control string”, arg1, arg2,….., argn); this statements write
the records into the file.
Example:
fprintf(fp, “%d %s %c %f”, no, name, sex, basic);
Error Handling During I/O Operations:
It is possible that an error may occur during I/O operations on a file. They are:
 Trying to read beyond the en-of-file mark.
 Device overflow.
 Trying to use file that has not been opened.

pg. 49
 Trying to perform an operation on a file. When the file is opened for another type
of operation.
 Opening a file with an invalid filename.
 Attempting to write to a write-protected file.
To overcome above problems the user uses two functions. They are
 feof()
 ferror()
feof():
function is used to check whether the file is reached to end of the file or not. This is used when the
user tries to read the contents from the file, once it reaches end of the file, a NULL is returned.
Syntax:
feof(file pointer);
Example:
feof(fp); where fp is the file pointer.
ferror():
This function reports the status of the file. it also takes only one argument and returns non-zero
integer if an error has been erected up to the point and returns 0 otherwise during the processing.

Types Of Files:
Files are classified into two types. They are:
 Text files
 Binary Files.
Text Files:
The data is written on to the file will be in the format of text which can easily be understand by the
user and also he can read the contents of the file. The whole data is clubbed together.
Example:
Just by typing the file at the prompt, the data in the file is displayed on to the
screen, which is shown below.
100nayeem2000.00
200liril3500.00
fscanf() and fprintf() are used for creating text files.
Binary File:
The data in this file will be in the format of the ASCII codes, which cannot be, understood by the user
and also he cannot read the contents of the file. fread() and fwrite() functions are used to create the
binary files.
fread():
It reads the data from the file as binary format.
Syntax:
fread( &(structure variable), sizeof(structure), n, <file pointer>);
example:
fread(&emp, sizeof(emp), 1, fp);
This example returns the number of items that read from the file emp.

pg. 50
fwrite():
It writes the data into the file in binary format.
Syntax:
fwrite( &(structure variable), sizeof(structure), n, <file pointer>);
example:
fwrite(&emp, sizeof(emp), 1, fp);
This example writes the number of items of data into the file emp.
Random Access to Files:
Some times user is much interested in accessing only a particular part of the file and not reading the
other parts. This can be achieved with the help of the functions fseek(), ftell() and rewind().
fseek():
This function is used to the set the file position to a desired point in the file.
Syntax:
fseek(file pointer, offset, position);
file pointer is a pointer to a file structure, offset is a number or variable of type long, which specifies
the number of positions to be moved from the location specified by the “position”. The position can
take any of the values.
Value Meaning
0 beginning of the file.
1 current position.
2 end of the file.
The offset may be positive, meaning move forwards, or negative, meaning move backwards, the
following examples illustrate the operation of the fseek function. They are:

Statement Meaning
fseek(fp,0L,0); Go to the beginning.
fseek(fp,1L,1); Stay at the current position.
fseek(fp,0L,2); Go to end of the file.
fseek(fp,m,0); Move to (m + 1)th byte in the file.
fseek(fp,m,1); Go forward by m bytes.
fseek(fp,-m,1); Go backward by m bytes from the current position.
fseek(fp,-m,2); Go backward by m bytes from the end.
When the operation is successful, fseek returns a zero. The user attempt to move the file pointer
beyond the file boundaries, an error occurs and fseek returns –1.
ftell():
This function gives the current position of the file in bytes.
Syntax:
<variable_name> = ftell(file pointer);
Example:
no = ftell(fp); where n is the valid c variable of type long integer and fp is the
file pointer. It returns the relative offset of the current position of the file.

rewind():

pg. 51
This sets the position f to the beginning of the file.
Syntax:
rewind(file pointer);
example:
rewind(fp); where fp is the file pointer. Takes the file pointer to the beginning
of the file.
Command Line Arguments:
The program, which executes at the prompt is said to be command line. It is a parameter supplied to a
program then the program is invoked. This parameter may represent a file name or a program, which
should be processed. A program is the file name where the executable code is stored. This execution
takes place at the prompt with the following parameters. These parameters are mentioned in the
main() function. It takes two arguments one is argc and other one is argv. The variable argc is of type
integer and it is known as argument counter, which counts number arguments supplied on the
command line. The argv to the pointer and it is of type character, it is known ad argument vector and
represents an array of character pointers that point to the command line. The size of this array will be
equal to the value of the argc. The first parameter in the command line is the name of the program.
Example:
<prompt> <program name> <file1> <file2>
from this the number of arguments are 3 that is argc = 3.
argv[0] = program name
argv[1] = file 1
argv[2] = file 2
Preprocessor Directives or Macros
C is a unique language in many respects at another unique feature of C language is preprocessor it
provides several tools that are unavailable in other high level languages. The programmer can make
use of these tools to make his program east to read, easy to modify, and more efficient. The
preprocessor implies the program that process the source code before it passes through the compiler.
Preprocessor are placed before the main(). If they are any preprocessor directive before the main
appropriate actions are taken and then the source program is handed over to the compiler. They all
begin with the symbol # and do not end with the semi colon (;) at the end. There are divided into three
categories. They are.
 Macro substitutions.
 File inclusion directives.
 Compiler control directives.
Macro Substitution:
It is a process where an identifier in a program is replaced by a predefined string composed of one or
more tokens. It is usually known as macro definition.
Syntax:
#define identifier string
Example:
#define pi 3.14
#define p printf

pg. 52
there are different forms of macro substitutions. The most common forms are:
 simple macro substitutions.
 Macro with arguments.
 Nested macro substitutions.
Simple Macro Substitution:
Simple string replacement is commonly used to define constants.
Program:
#define p printf
#define ms “Welcome to C”
main()
{ p(ms);
}
Macro With Arguments:
macro can have arguments. The argument of the macro name is replaced with the actual argument of
the macro name, which is encountered in the program. subsequent occurrence of a macro with
argument is knows as a macro call. Macro substitute means the macro expansion, the C source
program passed to the compiler only after the macro expansion processing is over.
Syntax:
#define identifier(f1, f2,….,fn) string
Example:
#define sqr(t) t * t
Program
#define sqr(x) x * x
main()
{
int m = 10, y = 11;
printf(“%d “, sqr(m));
printf(“%d”, sqr(y+1));
printf(“%d”, sqr(13));
}
Nested Macro:
Program
#define max(x, y) (x > y ? x : y)
#define main(x, y) ( x < y ? x : y)
main()
{
int a = 10, b = 23;
printf(“%d”, max(a, b));
printf(“%d”, min(a, b));
}

pg. 53
File Inclusion Directive:
This preprocessor directive is used to include another file, which contains functions or macro
definitions.
Syntax:
#include “filename”
#include <filename>
#include <header file>
#include “header file”
Example:
#include “test.c”
#include <test.c>
#include <conio.h>
Compiler Control Directives:
#if and #endif:
these are conditional compilation directives. An expression which is followed to the #if is evaluated if
the result is true than the corresponding block of statements will be complied between #if and #endif
other wise it skips the statements.

Syntax:
#if (expression)
statements;
#endif
Program: #define flag 0
main()
{ #if (flag == 0 )
printf(“It Is True.”);
endif
printf(“It Is Not True.”);
}
#else:
#else is used with #if preprocessor directive. It is same as else statement in if else control statement.
First #if is evaluated if the result is false then #else part is compiled.
Syntax:
#if (expression)
statements;
#else
statements;
#endif
Program
#define flag 0
pg. 54
main()
{
#if (flag == 0 )
printf(“It Is True.”);
#else
printf(“It Is Not True.”);
endif
}
#elif:
nesting of #if and #else is possible and this can be done by #elif. Every # elif has one expression and
this expression is evaluated, if the value is true then the corresponding code is compiled and all other
#elif expression are skipped.

Program
#define flag 0
main()
{
#if (flag == 0 )
printf(“Zero.”);
#elif (flag == 1)
printf(“One.”);
#endif
}
Stringizing Operator:
This operator # is used within the definition of macro function which is to be converted to a string.
Program
#define macro(m) #m
main()
{
printf(marco(understood # ));
}
The stringizing operator # converts printf function to printf(“understood #”)
Token Pasting Operator (##):
Token pasting operator is used to concatenate two tokens within a macro definition into a single
token .
Program
#define single(c, d) c ## d
main()
{
char a = “Hello”;
char b = “C”
printf(“%s”, single(a, b));
pg. 55
}

pg. 56

You might also like