You are on page 1of 67

St.

Mary‛s School of Management Studies


Jeppiaar Educational Trust 

C programming
· It is a middle level language i.e. it supports high level as well as low­level 
programming.
· Developed by Dennis Ritchie at Bell Lab, 1972. 
Advantages of C Language 
1) Robust language
· It has rich set of built in functions and operators can be used to write any complex 
program.
· The language is well suited for writing system software and business packages, 
because it combines the capabilities of an assembly language. 
2) Efficient and fast
· Due to its variety of data types and powerful operators.
· Limited no of keywords (only 32 keywords) 
3) Portable
· It means that a C program written for one type of the computer can be run on 
another type of the computer with little or no modification. 
4) Expandability
· Existing program or function may be included into another program is called 
expandability. 
5) Modularity
· It Supports modular programming. 
The property of dividing a big problem into sub problems is called as modularity. 
Where the sub problems are called as modules or functions or sub problems.
· Advantages of modularity 
a) Workload can be divided and shared by more than programmers. 
b) Errors can be identified and corrected easily. 

Structure of C program 
A C program has the following format: 

Documentation section 
Link section 
Definition section 
Global declaration section 
Main () function section 

Local declaration part 
Statement 1;  ­­­­­­­ 
Statement 2; 
….                                Executable statements / procedural statements 
…. 
Statement m;  ­­­­­­­­

________________________________________________________________________ 
Programming in C Page: ­ 1 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

subprogram section 

function header 1( ) 

variable declaration; 
statement 1; 
statement 2; 


statement n; 

function Header 2() 

.. 
.. 
….. 

function Header n() 




Documentation section
· Set of comment lines  can be given to specify the name of the program, the author 
and the other details which the programmer would like to use later.
· There are two formats to enter the comments about the problem 
(i)Start with // if the comment is of one  line 
(ii)Start with /* and end with */ if the comment is of multiple lines 
Link section
· It is used  to link functions from the system library or from another C program. 
The format is      #define the Header file name / C program name 
Enclosed in double quotes 

Data Definition section
· The  symbolic constants are to be declared in this section. Some of the values of 
the variables are constant throughout the program. This type of constant is called 
as the  Symbolic constant.

________________________________________________________________________ 
Programming in C Page: ­ 2 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Global declaration section
· The variables which  are used in more than one functions are called global 
variables. They should be  declared in this section before all the functions. 

main() function section

· Is  a  subroutine  /  function  that  consists  one  or  more  statements  designed  to 
perform a specific task

· Each functions consists of  two parts. They are 
(a)  Declaration part ­  It  declares all the local variables used in the function. 
(b) Executable part : It is for defining the executable / procedural statements.

· The two parts appear between the opening and the closing braces.

· All  the  procedural  statements  and    declaration  statements  parts  end  with 
semicolon.

· Every  C  program  must  have  a  main()  function  section  from  which  the  program 
starts it execution. 

Subprogram section
· Contains all the user­defined functions that are called in the main function.
· All sections, except the main function section may not be present when they are 
not required. 

Constants
· The fixed values that do not change during the execution of a program are called 
as the constants. There are two types of constants. They are 
(i)  Numeric constants 
(ii)  Non – Numeric constants 
(i)   Numeric constant
· It is a collection of numeric digits with the special characters  + , ­ and . There are 
two types of numeric constants. They are 
a) Integer constant
· It refers to a sequence of digits, doesn’t have any decimal point. Example: 15, 
+25, ­32 are the Integer constants. 
b) Float constant
· It refers to a sequence digits with a decimal point. Example: 7.52, +16.543, ­23.14 
are the float constants. 
Note:­  A float constant can be expressed in the following form also. 
7.52 can be expressed as .752e 1  or .752E 1  or .752E +1  or .752e +1

________________________________________________________________________ 
Programming in C Page: ­ 3 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

(iii) Non Numeric constants 
It is a collection of one or more numeric characters. They are 
a) Single character constant
· Contains a single character enclosed within a pair of single quote marks. 
Example: ‘X’, ‘e’, ‘5’, ‘*’ 

b) String constant
· Sequence  of  characters  enclosed  within  double  quotes.  The  character  may  be 
letters, numbers and special characters. For example: “Hello1”, “ St.mary's school 
of management studies”, “?….!”, “5+3” 

Note : A float constant can be expressed in exponent form. The exponent form has the 
following format: 
Mantissa Part e exponent  Part 
The value 3.4500 can be expressed as 0.345 e 1 , 345.0e­2, etc. 

Variable : It is a quantity whose value can be changed during the execution of the 
program.
· It is  a data name used to store data value.
· A variable may take different values at different situations  during execution.
· A variable name can be chosen by the programmer in meaningful way, i.e. it 
reflects the function or nature of the program. For example: amount, height, 
salary. 

The Rules for forming the variables are:­

· Must begin with an alphabet
· Length of 36 characters.
· Uppercase and lowercase are significant. The variable Total is different from the 
variable total.
· Should not be a keyword. The keywords are the words reserved for doing some 
operations such as printf, scanf, etc.
· White space not allowed. 

According to the availability their values , the variables are divided into two types. They 
are 

Global variable
· If a variable is used in all the functions then the variable is called global variable 
Local variable
· If a  variable is used within a function only , the variable is the local variable. The 
variable should be declared inside the function.

________________________________________________________________________ 
Programming in C Page: ­ 4 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Character set 
A set of characters, which are used to write the program
· Alphabet(a..z, A..Z)
· Numeric digits(0­9)
· Special characters(+,­,*,% etc.,) 
Symbolic constants 
If  the  value  of  a  variable  is  not  altered  through  out  the  program,  the  constant  is  the 
symbolic constant. Sometimes it called as a constant identifier. For example, the value of 
pi is always 22/7 where the value remains constant for the variable pi. 
General format  for defining a symbolic constant 

#define   symbolic_name    value_of_constant 

Rules for defining the symbolic constants are 

(i)  There is no space between  # and define 
(ii) There is a space between define and symbolic_name and also between 
symbolic_name and value_of_constant 
(iii) A program may have more than one symbolic constant 
(iv) Only one symbolic constant can be defined using a single #define 
(v) It should not end with semicolon 
(vi) For differentiating symbolic name and the variable the symbolic_name may be given 
in upper case. 
(vii) The value of the symbolic_name cannot be altered within the program. 
Example: 
# define  PI  3.14127 
# define  COLLEGE  “St.Mary’s” 

Input output functions 
In C Language , there are no input and output statements. To do inputting and outputting , 
some functions are used. The functions are called as the Input / Output functions ( I/O 
functions). 

The function  which is used to give the value of variable through keyboard is called input 
function. The function which is used to display or print the value on the screen is called 
output function. 

Note : ­ In C language we use two built in functions, one is used for reading and another 
is  used  for  displaying  the  result  on  the  screen.  They  are  scanf()  and  printf()  functions. 
They are stored in the header file named stdio.h. 

General format for scanf( ) function 

scanf(“control string”, &variable1, &variable2,……)
________________________________________________________________________ 
Programming in C Page: ­ 5 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

The control sting specifies the field format in which the data is to be entered. 
%d –integer 
%f – float 
%c­ char 
%s – string 
% ld – long integer 
%u – Unsigned Integer 

Example: 

scanf(“%d”,&x)  – reading an integer value, the value will be stored in x 
scanf(“%d%f”,&x,&a) ­  reading a integer and a float value In the above scanf ( ) 
function , we don’t use any format. This type of Input is called as the Unformatted Input 
function. 

Formatted input 

We can specify the field width when we are reading the value. The field 
speciation for reading the number is  %wd 
Where   w – is the field width of the number to be read . 

Example 

scanf(“%2d %5d”,&num1,&num2) 
data line is  50 31425 
the value 50 is assigned to num1 and 31425 is assigned to 31425. suppose the input data 
is as follows 
31425 50 , then the variable num1 will be assigned 31 and num2 will be assigned to 425 
and the 50 is unread. 
An input field may be skipped by specifying * in the place of field width. 
Example the statement   scanf(“%d %*d %d),&a,&b); will assign the data  123 456 789 
as follows:   123 is assigned to a ,    456 skipped   because of  * and  789 to b 

Output Function : To print the value on the screen or to store the value on the file, the 
output functions are used. printf() is the function which is use to display the output on the 
screen. 

The General format of the printf() function is 

printf(“control string”,variable1,variable2,…..) 

Example 
printf(“%d”,x) – printing the integer value x. 
printf(“%d%f”, x,a)­ printing a integer and float value using a single printf function.

________________________________________________________________________ 
Programming in C Page: ­ 6 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Formatted output :; Like formatted input , there is a formatted output also to have the 
output in a format manner. 
In this control string  consists of three types of items.
· Characters that will be printed on the screen as they appear
· Format specification that define the output format for display of each item
· Escape sequence characters such as 
\n –  new line 
\b – back space 
\f – form feed 
\r – carriage return 
\t ­  horizontal tab 
\v – vertical tab 

The format speciation is as follows 
%w.p type specifier 

w is an integer number that specifies the total no of columns for the output value and p is 
the another integer number that specifies the number digits to the right of the decimal 
point. 
Examples 
printf(“\n”); 
printf(“a = %f\n b = %f”,a,b); 
printf(“”sum = %d “,1234); 
printf(“%6d”,9876) 
printf(“%­6d”,9876) 
printf(“%06”,9876); 
printf(“%7.2f”,y); 
printf(“%­7.2f”,y); 
printf(“%10.2e”,y); 
printf(“%11.4e”,­y); 

Data types 

Data type specifies the type of data which is going to be assigned for a variable. 
There are four  types of data type

· Primary data type – Available in most of the computer languages.
· User­defined data types – Data type created by the user
· Derived data types (arrays and structures) – Data type to be used for grouping 
more than one data.
· Pointer Data type  ­ Data type to declare a pointer variable
· Empty data set (void) – Data type which has nothing.

________________________________________________________________________ 
Programming in C Page: ­ 7 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Primary data type 
The data type which is available in most of the languages is called as the primary data 
type. It is also called as the standard data type. 
1) Integer data type
· Signed int – 16 bits, both +ve and –ve values, range –32768 to 32767
· Unsigned int –16 bits, only positive values, range 0 to 655535
· Signed short int – 8 bits , both +ve and –ve values, range –128 to 127
· Unsigned short int – 8 bits, only positive values, range 0 to 255
· Signed long int – 32 bits, both +ve and –ve values, range – 214748364 to 
2147483647
· Unsigned long int – 32 bits, only positive values, range 0 to 4294966295 

2) Floating data type
· Float
· Double
· Long double 

3) Char data type
· signed char
· unsigned char 

User defined data type 

A data type which is created by the user is called as the user defined data type. 
There are two types of user defines data types. They are 

1) typedef 
It is used to give a name to the available data type. The general format is 
typedef datatype name; 
typedef int x; 
Now we can declare the integer variables a and b  like the following 
x a,b; // which is equivalent to int a,b; 

2) Enumerated data type 
Which can be used to declare variables that can have one of the values enclosed 
within the braces(known as enumeration constants). The general format is 
enum identifier {value1,value2,…..valuen}; 
enum identifier v1,v2,….vn; 
The enumerated variables v1,v2,..vn can only have one of the values 
value1,value2..valuen. the assignments of the following types are valid. 
v1=value3 
v5=value1 

Example
________________________________________________________________________ 
Programming in C Page: ­ 8 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

enum day {Monday, Tuesday,Wednesday……..Sunday}; 
enum day week_st,week_end; 

week_st=Monday; 
week_end=Friday; 
Note:­ 
The  compiler  automatically  assigns  integer  digits  beginning  with  0  to  all  the 
enumeration constants. That is value1 is assigned to 0 value2 is assigned to 1 and so on. 
The  automatic  assignments  can  be  overridden  by  assigning  values  explicitly  to  the 
enumeration constants. 
enum day {Monday=1,Tuesday,…..Sunday}; 
The remaining constants are assigned values that increase successively by 1. 

Declaration of Variables: 
A variable is a name given to the constant which is used in the program. All the variables 
used in the program should be declared in the declaration part. The declaration specifies 
what type of data is going to be held by the variable. The general format for declaring the 
variable is 

Datatype v1, v2, v3,  ......   vn; 

Where 
v1 , v2 ,.... vn are the varaibels 
datatype specifies which type of data can be assigned to the variables v1, 
v2, .... vn. 
More than variables with the same datatype can be declared using a single statement. 

Example : 

int x , y , z; [ the variables x , y and z are the integer variables and the values assigned for 
the variables must be integer  constants ] 
float a , b;    [ the variables x , y and z are the float variables and the values assigned for 
the variables must be float constants ] 
char c            [ the variables c is  the character variables and the values assigned for the 
variables must be character constant ] 

Note : The declaration variables should be done immediately after the opening brace of 
the program . 

Assignment Statement : 

It is a statement which is used for  assigning a constant value , a value of another variable 
or an expression to a variable.

________________________________________________________________________ 
Programming in C Page: ­ 9 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

The general format for the assignment statement is 

Variable = value / variable / Expression; 

(i)  If R.H.S has a value , the value is assigned for the variable lies on the L.H.S. 
(ii)  If R.H.S has a variable, the value of the variable on the R.H.S is assigned to 
the variable on the L.H.S 
(iii)  If R.H.S has an expression, the value of the expression is found first. Then the 
value of the expression  is assigned to the variable on the L.H.S 

After the  a value is assigned to a variable, that value is assigned automatically whenever 
the variable is used. 

Expression : 

It is a collection of variables and  constants with the operators. There are three types of 
expressions. They are 

(i)  Arithmetic expression : An arithmetic expression is an expression in which 
the variables and constants are combined with the arithmetic operators. The 
arithmetic operators are 

*  ­  Multiplication 
/  ­  Division 
+  ­  Addition 
­  ­  Subtraction 
%  ­  Modulo divisor 

Examples for arithmetic expression 

a.  a + b % 35 
b.  z – 25 + 45 

(ii)  Relational expression : A relational expression is an expression in which the 
variables and constants are combined with the relational operators. The 
resultant value of a relational expression is either true or false. The relational 
operators are 

<  ­  Lesser than 
>  ­  Greater than 
< =  ­  Less than or equal to 
> =  ­  Greater than or equal to 
= =  ­  Equal to 
! =  ­  Not Equal to

________________________________________________________________________ 
Programming in C Page: ­ 10 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Examples for relational expression : 

(a)  a >= b  [ true if the value of a is greater than or equal to the 


value of b. otherwise it is false ] 
(b)  b = = c  [ true if the value of b is equal to the value of c, 
otherwise the value is false] 
(c)  a < ( b  + c )   [ true if the value of a is lesser than the value of b + c 
, otherwise the value of the  expression is false] 

(iii)  Logical  expression : A Logical expression is an expression in which the 
variables and constants are combined with the Logical operators. The logical 
operators are 

&&  ­  AND 
| |  ­  OR 
!  ­  NOT 
Actually the operators are used to combine more than one relational expressions 
the format 

Relational expression 1  logical operator relational expression 2 
{  } 
­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ 
Logical Expression 

The result of the relational expression is also either true or false. 

The relational expression is evaluated as 
(a)   If more than one relational expressions  are combined with the && operators , the 
logical expression is true only if all the relational expressions are true. 

(b)  If more  than one relational expressions  are combined with the | | operators , the 
logical expression is true only if any one of the      relational expressions is true. 

(c) ! is the negated operator. If the relational expression followed by this operator is false, 
the logical  expression is true. 

Examples for arithmetic expression : 
a. ( (a > b ) && ( a > c ) ) 
b. ( ( Mark1 > 50 ) | | ( Mark2 > 50 ) ) 

Evaluation of an expression

________________________________________________________________________ 
Programming in C Page: ­ 11 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

If an arithmetic expression is given, there are some rules to be followed to evaluate the 
value of it. These rules are called as the priority rules. They are also called as the 
hierarchy rules. According to these rules, the expression is evaluated as follows; 

Rule 1 :­  If an expression contains parentheses , the expression within the parentheses 
will be performed first. Within the parentheses , the priority is to be followed. 
Rule 2 :­ If it has more than parentheses , the inner parenthesis is performed first. 
Rule 3:­  If more than one symbols of same priority , it will be executed from left to 
right. 

Example for evaluating an expression 

Let X = 2 , Y =5 then the value of the expression 
(((  Y ­ 1 ) / X ) * ( X + Y ) ) is calculated as:­ 

First evaluation is done on the innermost parenthesis 
(  Y ­ 1) = ( 5 ­ 1 ) = 4 = T1 
Second evaluation in done on next outer parenthesis 
(  T 1 /  X ) = ( 4 / 2 ) = 2 = T2 
Third evaluation is made on the next set parenthesis 
( X + Y ) = ( 2 + 5 ) = 7 = T3 
Last evaluation is for finding the value of whole expression 
(  T2 * T3 ) = ( 2 * 7 ) = 14 
The evaluations are made according to the priority rule. 

Type conversion 

The process of converting the data from one type to another type is called type 
conversion. There are two types of type conversion. They are 

(i)  Implicit type conversion 
(ii)  Explicit type conversion. 

1)  Implicit type conversion 
The conversion which is automatically done by the compiler is called automatic type 
conversion. Since this type conversion is done automatically, the data type conversion is 
called as the automatic type conversion. 

Example:  If a statement is used as    c=a/b; Where a is a float and b is an integer. Then 
the expression is the mixed data type expression. When a mixed data type expression is 
found in the expression, the compiler converts the result of the expression  into the data 
type of the operands which takes more number of bytes. Hence ‘ b’ is of integer data type 
, the value is automatically converted into float though ‘b’ is  integer.

________________________________________________________________________ 
Programming in C Page: ­ 12 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

2) Explicit type conversion 

Instead of automatic type conversion , the user can change type of the data in an 
expression. It is called as the explicit data type conversion. It is also called as the type 
casting. 

For type casting the general format is 

(datatype) operand; 

where the operand may be either a variable or a constant. 

Example 

Assume that the 10 and 3 are the values of two integers a and b respectively.  After the 
statement 
c=a/b; 
is evaluated , the value of c is 3.0 only even though c is float 

Instead , if the type casting is made as the following statement 
c=(float)a/b; 
the value of c is 3.3333. 

Note:­ 
Type conversion is not changing the type of variable. Instead it changes the datatype for 
the value of the variable. 

OPERATORS: 

An operator is a symbol used for doing an operation. The operators are used for 
mathematical or logical manipulations. There are six types of C Operators. They are 

(i)  Arithmetic Operators 
(ii)  Relational Operators 
(iii)  Logical Operators 
(iv)  Assignment Operators 
(v)  Increment and Decrement operators 
(vi)  Conditional Operators 

Arithmetic Operators: These operators used for forming arithmetic  expression ( 
mathematical expression ). 

Relational Operators: These operators are used for defining the relational expression.
________________________________________________________________________ 
Programming in C Page: ­ 13 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Logical Operators :  These operators are used for combining more than one conditions. 

Assignment Operators: These are the ‘short hand ‘ assignment operators. The general 
format of this operator is 

Variable operator = expression; 

Where the operator is the binary arithmetic operator. 

The above assignment statement is equivalent to variable = variable operator expression; 

For example: 

The statement x = x * 100; 

Can be written as x * = 100 ; by using the assignment operator. 

By using these operators , the variable on the L.H.S need not be repeated again. 

Increment and Decrement Operators:. These operators are used for incrementing and 
decrementing the value of variable. There are two formats for writing the  Increment 
operators. They are 

1. Post increment operator  which has the form Variable  + +; 
2. Pre increment operator  which has the form + + Variable ; 
Both are same till they are not assigned to variables. 

Example: 

Let x = 1; 
Then after executing the statement x ++ ; The value of x is 2. Instead of the post 
increment operator , if we use the pre increment operator ++ x, the value is also 2. 

Otherwise if they are assigned to another variable, the post increment operator assigns the 
initial value first and then it is incremented where as the pre increment operator assigns 
the value after the variable is incremented. 

Example: 

x = 1;  x = 1; 

y = x ++;  y = + + x;

________________________________________________________________________ 
Programming in C Page: ­ 14 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Code 1  Code 2 

For the code 1 , the value of y is 1 and for the code 2 the value of y is 2. In 
both the cases , the value of x is 2. 

Like the increment operators , there are two formats for writing the  Decrement operators. 
They are 

1. Post Decrement operator  which has the form Variable  ­ ­; 


2. Pre Decrement operator  which has the form ­ ­ Variable ; 
Both are same till they are  not assigned to  variables. 

Example: 

Let x = 1; 
Then after executing the statement x  ­ ­ ; The value of x is 0. Instead of the post 
decrement operator , if we use the pre decrement operator ­ ­  x, the value is also 0. 

Otherwise if they are assigned to another variable, the post  decrement operator assigns 
the initial value first and then it is decremented where as the pre decrement operator 
assigns the value after the variable is decremented. 

Example: 

x = 1;  x = 1; 

y = x  ­ ­ ;  y = ­ ­ x ; 

Code 1  Code 2 

For the code 1 , the value of y is 1 and for the code 2 the value of y is 0. In 
both the cases , the value of x is 0. 
Conditional Operators : These operators are used for the conditions. These operators 
are also called as the ? : operator. The general format of the operator is 

Variable = Condition ? a.e 1 : a.e 2; 

Where 
Condition is either a relational Expression  or Logical Expression 
a.e 1 and a.e 2 are arithmetic expressions.

________________________________________________________________________ 
Programming in C Page: ­ 15 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

If the condition is true ,  the value of the arithmetic expression  1 is assigned to the 
variable on the L.H.S. Otherwise , the value of the arithmetic expression 2 is assigned to 
variable. 

Example: 

big =  (x > y ) x : y; 

for the above statement if the values of x and y are 10 and 12 , then big = 12 because the 
condition is false, so the value of the expression 2 ( that is the value of y ) is assigned to 
big.  If the values of x and y are 100 and 10 , then big = 100 because the condition is true, 
so the value of the expression 1 ( that is the value of x ) is assigned to big. 

Special Operators : There are special operators are available in C. They are 

(a) sizeof( ) operator :­ This operator is used to find the size of the variable or the size of 
the data type. The general format is 
sizeof ( variable / data type ); 
The operator returns the size of the variable or the data type in terms of bytes. 
Example:­ 
n = sizeof(int); // n = 2 since int takes 2 bytes 
m = sizeof( x ); // m = 2 if x is an integer variable , or m =4 if x is a float etc., 

Comma operator :­ It is an operator which is used to combine more than one statements 
into a single statement. The statements 

x = 10; 
y = 20; 
z = x + y; 
can be written in a single statement by using the comma operator as 
z = ( x + y , x = 10 , y = 20 ); 
Bit wise operators:­  Some operators can be used to do the bit wise operations. A bit is a 
binary digit whose value either 0 or 1. 

The Bit wise operators are 

& ­ Bit wise AND 
| ­ Bit wise OR 
! – Complement 
>> ­ Shift right 
<< ­ Shift Left 
­  Exclusive OR

________________________________________________________________________ 
Programming in C Page: ­ 16 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Structures in a C program 

A C program is a collection of different C statements in which each statement ends with 
semicolon.  According to the flow of execution of the statements , it has three types of 
structures. 

1.Sequential Structure : It is a structure in which the statements are executed 
sequentially one after another. That means , the flow of execution goes to statement i + 1 
after the ith statement is executed. The statements are normally executed in the order in 
which they appear in the program 

2.Selective structure : It is a structure in which the statements are not executed 
sequentially.. It means that the flow of execution goes to statement k (which is not equal 
to i + 1)  after the ith statement is executed. The statements are not executed in the order 
in which they appear in the program. 

3.Repetitive structures : Some statements within a program are executed more than 
once. That means , the  of execution for the statements  i to m are done more than one 
time. The statements are normally executed as long as a condition is true. It exits only if 
the condition becomes false. 

1.Selective Structure 
These structures are used for doing the decision making operations such as 
a)  which is greater whether A  or B? 
b)  who has got more marks of the persons P1, P2 ,... , Pn? 
c)  What action is to be done if failure occurs? 
These structures are also called as the decision making structure. The statement which 
selects what action is to be done among the actions is called as the control statement. 

Statement chooses the action to be performed 

Action 1  ( Collection of one or more statements) 

Action 2  ( Collection of one or more statements) 

........ 

....... 

Action n  ( Collection one or more statements ) 
From the actions , one of the action is to be done according to a statement. That statement 
is the control statement.

________________________________________________________________________ 
Programming in C Page: ­ 17 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Example:­ 

If  ( sex is male ) 
Action type 1 is to performed 
Else 
Action type 2 is performed. 

In the above example, either action type 1 or action type 2 is selected according to the 
value of sex. So this type of the statement is the control statement. In this case , if the sex 
is male, the flow is not altered. But in the case of  sex is female, the flow is altered. After 
the control statement is executed, the flow goes to the first statement in the action type2. 

There are two types of control statements. They are 

a)  Conditional control statements : The flow is altered according to a  condition. where 
the condition is a statement whose value will be either TRUE or FALSE.  It is also called 
as the Selective Structure. The Relational and Logical expressions are the conditions. 

The  conditional control statements are 
1.  If structure 
2.  Switch ... case structure 

b)  Un Conditional control statements : The flow is altered without any condition. 

The un conditional control statements are 

goto 

a. Selective  Structure with If statement: 

Classification of if structures. 

The  If statement  has the following types. 

1.  Common If 
2.  If . . else 
3.  Nested If 
4.  Multi alternative 

The Common IF has the following format 

If ( condition ) block ;

________________________________________________________________________ 
Programming in C Page: ­ 18 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Where the condition may be a relational or logical expression and the block may be have 
a  single statement or more than one statements opens with { and closes with }. 

In the format ,

Case 1 :  The block is selected for the execution only if the condition is true. After 
executing the statement / statements  within the block, the flow comes to the next 
statement of the block.
Case 2 :   The block is not selected for the execution if the condition becomes false. 
Without  executing the statement / statements within the block, the flow comes to the 
next statement of the block. 

Example: 

If ( marks < =50 ) printf(“\n Performance not Good ,  Prepare Well for the next exam”); 
The flow of execution is represented in the flow chart as 

Checks the  TRUE 
condition 

FALSE  Executing the Block 

Statement X

The IF.. else  has the following format 
If ( condition ) block 1; 
else block 2; 

Where the condition may be a relational or logical expression and blocks may have a 
single or more than one statements opens with { and closes with }. 
In the format , 

________________________________________________________________________ 
Programming in C Page: ­ 19 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Case 1 :  The block is selected for the execution only if the condition is true. After 
executing the statement / statements  within the block, the flow comes to the next 
statement of the block. 
Case 2 :  The block2 is  selected for the execution if the condition becomes false.After 
executing the statement / statements within the block 2 , the flow comes to the next 
statement of the block2. 

Example: 
if ( marks < =50 ) printf(“\n Performance not Good , Prepare Well for the next exam”); 
else printf(“\n Performance  Good , Keep it UP”); 

The flow of execution is represented in the flow chart as 

Checks  TRUE 
condition 

FALSE 
Executing the Block 1 
Executing Block 2

Statement X 

The Nested If  is an if structure in which more than one if structures are overlapped. That 
is , if an if lies within another if  , the if structure is called as the nested if. 

The general format of nested if is 

If ( condition 1 ) 

if (condition 2 ) block 1 
else block 2 

________________________________________________________________________ 
Programming in C Page: ­ 20 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

else 

if (condition 3 ) block 3 
else block 4 

In the above format, the condition 1 is checked first. 
If it is true, then condition 2 is  checked 
if it is also true, block1 is executed. 
if it (condition 2) is false , block2 is executed. 
If it ( the condition 1)  is  false 
then condition 3 is  checked 
if it is also true, block3 is executed. 
If it (condition 3) is false , block4 is executed. 

FALSE  checks  TRUE 


condition 1 

FALSE  TRUE 
FALSE  checks  TRUE  checks 
condition 3  condition 2 

Execute block4  Execute block3  Execute block2  Execute block1 

Statement X

________________________________________________________________________ 
Programming in C Page: ­ 21 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Example  if ( cust_cat==’A’) 
if ( salary < 2500 ) bonus = 1000;else bonus= 750; 
else  if (salary<5000)bonus=1500; else bonus=0; 

In the example, bonus=1000 if customer category is A and getting salary less than 2500. 
Or bonus=750 if customer category is A and getting salary greater than or equal to  2500. 
Or bonus=1000 if customer category is not A and getting salary less than 5000no bonus 
is given if customer category is not A and getting salary greater than or equal to 2500. 
The Multi alternative if  structure has the following format 
if ( condition 1 ) block1; 
else if (condition 2) block2; 
else if (condition 3) block 3; 
................. 
................. 
else block n; 
statement – X; 
In the above format, block 1 is executed only if the condition 1 is true. After the 
execution , the flow goes to the statement – X. 
If the condition 1 is false, it checks whether the condition 2 is true. If it is true  , block 2 
is executed.  After the execution , the flow goes to the statement – X and so on. 
If no condition is true , block n is executed. 

Checks  FALSE 
condition 1 

TRUE 

checks  FALSE 
Block 1  condition 2 

TRUE 
TRUE  checks  TRUE 
Block 2  condition 3 

Block 3 

Block n
________________________________________________________________________ 
Programming in C Page: ­ 22 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Note : The multi alternative if structure is also called as the else if ladder. 

2.          Selective  Structure with  switch ... Case structure 

This structure is used for doing multi way decisions such as else if ladder. It is an 
alternate structure for else if ladder. 

The general format for the switch .. case structure is 

switch  ( e ) 

case op 1:  block 1; 

case op 2 : block 2; 

case op 3: block 3; 

........... 

............ 

........... 

default: 

block n; 

Statement – x; 

In the above format , e may be an expression or may be character or integer variable. 
The options op1 , op2 , ...... are the constant values for e. 

Each block except block n has a break statement. 

The block 1 is executed if the value of e is equal to op1. After the block is executed , the 
flow moves to the statement – x by means of the break statement in the block. 

The block 2 is executed if the value of e is equal to op2. After the block is executed , the 
flow moves to the statement – x by means of break statement in the block.

________________________________________________________________________ 
Programming in C Page: ­ 23 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

The block n is executed if the value of e does not match with any optional values  op1, 
op2, ..... . op n­1 . After the block is executed , the flow moves to the statement – x 
automatically. 

Example for switch .. case 

switch (cust_cat ) 

case  ‘A’: discount = price * 10.0 / 100; 
break; 
case  ‘B’: discount = price * 7.5 / 100; 
break; 
case  ‘C’: discount = 100; 
break; 
default: printf(“\n Invalid customer Category”); 
discount=0 

b)  Un conditional control statement using go to 

The flow is altered without checking any condition. The general format of go to is 

go to label name; 

where label name is a label given for the statement for which the flow is sent. The rules 
for defining the variables are to be used for labeling the statement. The label for a 
statement should be given in the format 

Label name : statement – X; 
Example :  main() 

int a,b , c = 1000; 
a = 100; 
b = 20; 
go to lab; 
c =  ­1000; 
printf(“\n Dummy”); 
lab:  print(“\n C value is %d”,c); 

The output for the above program is  C value is 1000. 
( The statements c = ­ 1000; and printf(“\n Dummy”); are not executed because as soon 
as the flow reaches to go to statement , the flow will be transferred to the 
printf(“\n C value is %d”,c); which has the label (lab).

________________________________________________________________________ 
Programming in C Page: ­ 24 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Repetitive Structure : It is a structure in which a block is to be executed more than once. 
This structure is also called as the Looping structure or Iterative structure . The block 
may be a single statement or a collection of more than one statements begins with { and 
ends with }. 
There are four  types of repetitive structures. They are 
(i)  While Loop (ii) Do .. while Loop (iii) For Loop (iv) Looping with go to statement 
(i) The While Loop : In this structure the block specified for the while loop is executed 
only if the condition is false. The general format of the while Loop is 
while ( condition ) block; 
where the condition may be a relational or logical expression. 

When  the while loop is executed , it first checks the condition. 
Case (i) : if the condition is true, the block is executed. After the block is executed , the 
control returns to the condition again and checks whether the condition is true now. If so, 
the block is executed again. The process is repeated as long as the condition is true. 
Case (ii): if the condition is false, the control is transferred to the next statement of while 
loop. 

The minimum number of iteration ( ie.,, when the condition is false ) of executing the 
block for while loop is 0. 
The flow chart for the while loop is 

FALSE  Checks  TRUE 


condition 
Executing the Block 

Statement X

Where Statement x is the statement which lies after the while loop. 

________________________________________________________________________ 
Programming in C Page: ­ 25 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Examples: 

1.  i=1; 
while ( i <= 10 ) 

printf(“%d\n”,i); 
i = i + 2; 

printf(“\n OK..”); 

the output of the above segment is 





OK.. 

2.  i=11; 
while ( i <= 10 ) 

printf(“%d\n”,i); 
i = i + 2; 

printf(“\n OK..”); 

the output of the above segment is 
OK.. 
In the second example, the block is not executed because the condition is false 
and the control does not enter into the block. 

(ii)The Do .. While  loop: When this loop is executed , the condition is checked after the 
block is executed once. The general format of the do .. while Loop is 

do

block; 
}while ( condition ) ; 

where the condition may be a relational or logical expression. 
When  the do .. while loop is executed , it executes the block once and then the condition 
is checked.

________________________________________________________________________ 
Programming in C Page: ­ 26 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Case (i) : if the condition is true, the block is executed again. After the block is executed 
, it again checks the condition whether it is  true. The process is repeated as long as the 
condition is true. 
Case (ii): if the condition is false, the control is transferred to the next statement of while 
loop. 

The minimum number of iteration ( ie., though the condition is false ) of executing the 
block for while loop is 1. 

Execute the Block 

Condition  TRUE 

FALSE 

Statement X

Where Statement x is the statement which lies after the do .. while loop. 
Examples: 
1.  i=1; 
do

printf(“%d\n”,i); 
i = i + 2; 
} while ( i <= 10 ); 

printf(“\n OK..”); 
The output of the above segment is 

________________________________________________________________________ 
Programming in C Page: ­ 27 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 




OK.. 

i=11; 
do { 
printf(“%d\n”,i); 
i = i + 2; 
} while ( i <= 10 ); 
printf(“\n OK..”); 
The output of the above segment is 
11
OK.. 
In the second example, the block is not executed because the condition is false and the 
control does not enter into the block. 
(iii)The for   loop: When this loop is executed , the condition is checked for each 
iteration.  The for loop has the following format 

for ( initialization part ; conditional part ; incremental / decremental part) 
block; 

When  the FOR loop is executed , the following  steps are done. 

Step 1:  Initialization part is performed first 
Step 2:  The condition is verified. 
Step 3:  If the condition is True , 
(a)  Block is executed 
(b)  The incremental or decremental part is done 
(c)  Again , the control goes to step (2) 

If the condition is False , 
The control goes to the statement which  lies after the For loop 
without executing the block. 

Examples: 

1.  for ( i =1 ; i<=8 ; i++)printf(“%d\n”,i); 
printf(“\n OK..”); 

The output of the above segment is 


3

________________________________________________________________________ 
Programming in C Page: ­ 28 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 






OK.. 

2.  for ( i =10 ; i<=8 ; i++)printf(“%d\n”,i); 
printf(“\n OK..”); 
The output of the above segment is 
OK.. 
Note : 
1.  All the parts are optional. So the following for loops are valid 
(a)   i = 1; 
for ( ; i < = 10 ; i = i + 3)printf(“%d\n”,i); 
printf(“OK..”); 
The output will be 



10
OK.. 
(b)   i = 1; 
for ( ;  ; i = i + 3) 

printf(“%d\n”,i); 
if ( i > 10 ) go to xyz; 

xyz:       printf(“OK..”); 
The output will be 



10
OK.. 
(c)    i = 1; 
for ( ;  ; ) 

printf(“%d\n”,i); 
i = i + 3; 
if ( i > 10 ) go to xyz; 

xyz:       printf(“OK..”); 
The output will be

________________________________________________________________________ 
Programming in C Page: ­ 29 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 




10
OK.. 

Note :­ A for loop within another for loop is called as the Nested for loop. 

for ( i =1 ; i <= 5; i++) 
for ( j = 10; j<=50 ; j = j + 10) 
printf(“%d\n”,i*j); 
The output of the above segment is 
10
20
30
40
50
20
40
60
80
.. 
.. 
.. 
50
100 
150 
200 
250 

(iii)  Looping with Go to : Repetitive structure can be formed by using the go to 
statement as 

i=1; 
xyz:    printf(“%d\n”,i); 
i = i + 3; 
if ( i <= 10 ) go to xyz; 
printf(“\n OK..”); 
The output of the above statement 



10

________________________________________________________________________ 
Programming in C Page: ­ 30 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

FUNCTIONS 
If a large or complex problem is given to be solved, it is difficult to maintain , test and 
debug the code of the program. If this program is divided into different parts, then they 
can be tested , debugged and maintained separately and these operations are very easy. 
Each part may be independently processed and are combined into a single unit to get the 
solution for the complex problem. The divided parts are called as the Modules. They are 
also called as the subroutines and functions. The functions in C can be easily defined and 
used. When the functions are used, we have the following advantages: 

1.  It supports the top­down programming approach. That is after defining the overall 
logic of the program in the calling function, we can define the called functions. 
2.  The code is reduced. 
3.  Errors or faults cane be identified easily. 
4.  A function in another program can be called to our current program. This property 
is called as the Expandability. 
5.  Time and space are saved. 

TYPES OF FUNCTIONS 

The functions of C are divided into two categories. They are 
a) Built­in­Functions :­  The procedures of the functions are defined previously. The 
user need not write the procedure for them. They are written by the manufacturer of 
compiler. Each built­in­function is stored in a filed called as the HEADER FILE.If a 
built­in­function is to be called, the corresponding header file is to be linked into the 
current program in the linkage section. 

b) User Defined Functions :­ The procedures for these functions are not defined already. 
The user has to create his / her own function. Since the functions is developed by the user 
, the function is called as the User Defined functions It is created at the time of writing 
the program. The main() function is one of the user defined function because the 
statements within the main() function  are to be written by the user. 

a)  BUILT­IN FUNCTIONS : 

The functions which are not written by the user are called as the Built­in­functions. The 
functions are available. These functions are called as the predefined functions. Some of 
the built­in functions in C are 
i)  Mathematical Functions :­ For doing some mathematical calculations in real time 
problem, we can use these functions such as sqrt , sinx , log etc,. The mathematical 
functions are stored in math.h library. If any of these function is to be called , the header 
file is to be included as 

#include <math.h>

________________________________________________________________________ 
Programming in C Page: ­ 31 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

When the program which uses the  mathematical functions is compiled, the header file , 
math.h is included automatically. 
Function  Purpose 

sqrt(x)  To find the Square Root of X 

sin(x)  To find the sine pf X 

cos(x)  To find cosine of X 

tan(x)  To find the value tan of x 

exp(x)  To calculate exponent of X 

log(x)  To calculate Log of X 

fabs(x)  To have the Absolute value of X 


pow (x,y)  To find the x 

floor(x)  To round down x to its nearest integer. 

ceil(x)  To round up x to its nearest integer. 

acos(x)  ­1 
To find the value of cos (X) 

asin(x)  ­1 
To find the value of  sin (X) 

­1 
atan(x) 
To find the value of tan (X) 

ii)   String Functions : These functions are used for processing the strings. A string is an 
array of characters. These functions are stored in a header file, string.h. if any function is 
to be called , the header file is to be included as 
#include <string.h> 

The string functions are

________________________________________________________________________ 
Programming in C Page: ­ 32 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

(i) strlen () – It is a function to find the length of the string.The general format is 
strlen(st)      where st is the string whose length is to be found 
Example : Assume that st=”BALA”,then strlen(st) is returning 4. 

(ii) strcpy() – It is a function to copy  the content of one string to another. The general 
format is 

strpy(st1 , .st2) 

where st1 is the destination string and st2 is the source string. 

Example :­ Assume that st2=”BALA”,then strcpy(st1,st2) is copying the string “BALA” 
to st1. 

(iii) strcat() – It is a function to concatenate one string to another. The general   format is 
strcat (st1,st2) 
where st1 is the destination string and st2 is the source string. When the 
function is used , the content of st2 is concatenated to content of st1 and the new string is 
stored in st1. 

Example :­ Assume than st1=”BALA” and st2=”RAMAN” . If we use strcat(st1,st2) , st1 
= “BALARAMAN”. 

(iv) strcmp() – It is a function to compare two strings. Its general format is 

strcmp(st1,st2) 
where st1 and st2 are the strings to be compared. The function returns 

0  ­  if both the strings are equal 
+ ve  ­  if  st1 is greater than  st2 
­ ve  ­  if st1 is lesser than st2. 
Example :­  Assume than st1=”BALA” and st2=”RAMAN” .The function 
strcmp(st1,st2)  returns –ve value. 

(iv) strrev() – It is a function to reverse a string. Its general format is 

strrev(st1) 
where st1 is a string to be reversed. The function returns 

Example :­  Assume than st1=”BALA” .After the function  strrev(st1); the value of st1 
is “ALAB”.

________________________________________________________________________ 
Programming in C Page: ­ 33 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

(iv) strcat() – It is a function to concatenatee two strings. Its general format is 

strcat(st1,st2) 
where st1 and st2 are the strings to be concatenated and the resulatant 
string is store in st1. 
Example :­  Assume than st1=”BALA” and st2=”RAMAN” .After the function 
strcat(st1,st2); is called , st1 = “BALARAMAN”. 

USER DEFINED FUNCTIONS 
A function which is written by the user is called as the Userdefined function.The function 
main() is also an  user defined function because the statements within it are written by the 
user. When a function is designed and packed , it is treated as a ‘black box’. The function 
takes a data from another function and returns a value.To give the data to a function , a 
call is made to call the function. 

Then the  function which sends the data to the function is called as the Calling Function 
and the function which is called by the calling function is called as the Called Function. 

Function 1  Function 2 

…………..  …………….. 
­­­­…….. 
……………  …………….. 

………….. a                   Sending the data  ……………. 

Finding some value 

Calling is made  …………….. 

Returning a value  ……………………

Function 1 is the Calling Function and 
Function 2 is the Called Function 
The general format of a Userdefined Function is 

Function name (argument list) 
Declaration part 1 

Declaration part 2 
Statement 1 
Statement  2 

________________________________________________________________________ 
Programming in C Page: ­ 34 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

­­­­­­­­­­­­­ 

­­­­­­­­­­­­­ 

­­­­­­­­­­­­­­ 

­­­­­­­­­­­­­­ 

Statement n 
return(exp) 

where  argument list consists of a variable or a collection of more than one variables 
separated by commas 

Declaration part 1 is for declaring argument(s) 
Declaration Part 2 is for declaring the local variable(s) used in the function. 
exp is an arithmetic expression. 
Statement 1, Statement 2 ,….. Statement n are C Executable statements. 

All parts are not essential.   A function can be written without any argument.A function 
returns the value by means of return statement. 

The rules for developing the userdefined functions are 

1)  The rules followed for forming variables are used for forming a function 
name. 
2)  The arguments must be enclosed within the parantheses. 
3)  A function is returning only integer value by default. 
4)  If a function returns a value which is other than integer, must de declared 
in the calling function explicitly. This method is called as the Functional 
prototyping. 
5)  The type specifier is to be given for  the userdefined function if it returns a 
non­integer value. 
6)  If a function does not return any value , the type specifier must be void. 
7)  The ‘plain ’ return can be given for the function if it does not return any 
value. 
8)  A function is called by using the function name in the statement. 
9)  If a function is returning a value , the function is called by using the 
following format

________________________________________________________________________ 
Programming in C Page: ­ 35 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Variable =   function name (arguments list ) where the datatype for the variable 
and  and the return datatype must be same. 
10)      If a function is returning a value , the function is called by using the 
following format  function name (arguments list ) 

11)  A  function should be used on the right hand side of the assignment 
statement. 
12)  Sometimes a function may not return a value. If so, the function doesn’t 
have return statement. 
13)  A function returns only one value at a time. 
14)  Local  variables which are used within the function are not valid outside 
the function. 
15)  A program may contain more than userdefined functions. 

TYPES  OF   FUNCTIONS 
According the arguments and the returning value , functions are divided into three 
categories. 

1)  A function with no arguments and no return value 
2)  A function with no arguments and return a value 
3)  A function with an argument or arguments and returning no value 
4)  A function with arguments and returning a value. 

1. FUNCTION WITH NO ARGUMENTS AND RETURN NO VALUE 


If a function does not have any arguments , it is  getting any value from the calling 
function. Also if it does not return any value , the called function is receiving any vale 
from the function when it is called. That is , there is no data transfer between the calling 
function and the called function. 

Function 1 Function 2 

f1(x)  f2( ) 
No input 
­­­­­­­­­­­­­­­­­­­­­  ……………… 
……………… 
Calling the 
function f2( )  Returning from the 
function 
­­­­­­­­­­­­­­­­­­­­  No output 
No data is 
Example :  transferred 
main( )  between the 
functions
________________________________________________________________________ 
Programming in C Page: ­ 36 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 


callwecome( ); 

void callwelcome( ) 

printf(“\n WELCOME”); 

main( ) is the calling function and callwelcome ( )  is the called function. Between the 
functions , no data is transferred. 

2. FUNCTION WITH NO ARGUMENTS AND RETURN A VALUE 


A function which does not get  value from the calling function can return a value. 

Function 1 Function 2 

f1(x)  f2( ) 
No input 
­­­­­­­­­­­­­­­­­­­­­  ……………… 
……………… 
Calling the 
function f2( )  Returning from the 
function 
­­­­­­­­­­­­­­­­­­­­  A value 
No data is 
Example :  transferred 
main( )  between the 
{  functions
int v; 
v=calltemp( ); 
printf(“\n The returned value form the calltemp( ) function is %d”,v); 

calltemp( ) 

return(1000); 

3.FUNCTION WITH AN ARGUMENTS OR ARGUMENTS AND RETURN


NO VALUE 

If a function has an argument or arguments , it is  getting one or more values from the 
from the calling function. Also if it does not return any value , the calling function is not 
receiving any value from the called function. That is ,  data is transferred from  calling 

________________________________________________________________________ 
Programming in C Page: ­ 37 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

function and the called function but no data is transferred from the called function to the 
calling function. 

Function 1 Function 2

f1(x)  sending  f2(x) 

­­­­­­­­­­­­­­­­­­­­­  ……………… 
……………… 
Calling the 
function f2( )  Returning from the 
function 
­­­­­­­­­­­­­­­­­­­­  No output

No data is 
transferred 
Example :  between 
main()  the 
functions 

int x,y,z; 
scanf(%d%d”,&x,&y); 
add(x,y); 

add(int a,int b) 

int c; 
c=a+b; 
printf(“%d”,c); 

where add() is the called function which has the arguments a,b and main() is the calling 
function. 

Types of Arguments : 
The arguments are also called as the parameters.There are  two types of parameters. 
They are 
i)  Actual Parameters: ­ The arguments or parameters used in the calling function to call 
the called function are called as the Actual parameters. In the above example, x,y are the 
actual parameters. 
ii) Formal parameters:­  The arguments or parameters used in the called function are 
called as the Formal  parameters. In the above example, a,b are the formal parameters. 

________________________________________________________________________ 
Programming in C Page: ­ 38 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

4. FUNCTION WITH AN ARGUMENTS OR ARGUMENTS AND RETURN


A VALUE 

A function can return only value at a time.If a function has an argument or arguments , it 
is  getting one or more values from the from the calling function. Also if it returns any 
value , the called function is  receiving a value from the calling function when it is called. 
Data is transferred from  calling function and the called function and vice­versa. 

Function 1 Function 2

f1(x)  sending  f2(x) 


data
­­­­­­­­­­­­­­­­­­­­­  ……………… 
……………… 
Calling the 
function fn2()  Returning from the 
function 
Receiving
­­­­­­­­­­­­­­­­­­­­  data

Example 1:

Example for a function returning an integer value: 

main() 

int x,y,z; 
scanf(“%d%d”,&x,&y); 
z=add(x,y); 
printf(“\n Resultant value is %d”,z); 

add(int a,int b) 

int c; 
c=a+b; 
return( c ); 

Function prototyping :­ 
If the called function returns an non integer value or not returning any value, has to be 
declared in the calling function. Only function header can be declared. It is called as the 
function prototyping. 

________________________________________________________________________ 
Programming in C Page: ­ 39 ­
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Example 2:

Example for a function returning a non­integer value: 

main() 

float  x,y,z; 
float div ( float , float ); 
scanf(“%f%f”,&x,&y); 
z=div(x,y); 
printf(“\n Resultant value is %f”,z); 
}

float div(float  a, float  b) 

float c; 
c=a / b; 
return( c ); 

In the above example , a type specifier is given  for the called function div ( ) . Also the 
function header is declared in the calling function. 

Note 1 :­ A function can call any function. Again the called function may call another 
function. The functions are called as the Nesting of  functions. 

Example : ­ 
main() 

int a,b,res; 
scanf(“%d%d”,&a,&b); 
res=difference(a,b);                              //     calling the function difference // 
printf(“\n Difference is %d”,res); 

difference(int x,int y) 

int dif; 
big=biggest(x,y);  //  calling the function biggest // 
if (big==x) dif=x­y;                             // called function for main() but it is the 
else dif=y­x;                                          // calling function for biggest 
return(dif);

________________________________________________________________________ 
Programming in C Page: ­ 40 ­
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 


biggest(int x,int y) 
{                                                                       // called function for difference 
if (x>y) return(x); 
else return(y); 

Note 2:­ Nesting of function calls also possible in C as 
c = div( div(a,b),c)   // which is equivalent to a / b / c. 

Note 3:­ A function calls itself is called as the Recursion as 
fact ( int n) 
{
int factorial; 
if (n<=1) 

factorial=1; 
return(factorial); 

else   factorial=n*fact(n­1); 

FUNCTION HAVING AN ARRAY AS ONE OF ITS ARGUMENT 
The values of an array can be passed to a function. If an array is to be passed to a called 
function , the following format should be used 
Return datatype  function name ( data type array name, data type size of the array ) 

Local Variable declaration; 
Statement 1; 
Statement 2; 
­­­­­­­­­­­­­­ 
­­­­­­­­­­­­­ 

Statement n; 

Example :­ 

biggest(  a , n ) 
int  a[  ],size; 

________________________________________________________________________ 
Programming in C Page: ­ 41 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

int big; 
big=a[ 0 ]; 
for ( i = 1 ; i < n ; i ++) if ( big < a [ i ] ) big = a[ i ]; 
return(big); 

biggest() is the userdefined function which is returning integer data by default. 
‘a’ is the array which has ‘n’ elements. 

FUNCTION HAVING A STRUCTURE AS ONE OF ITS ARGUMENT 
The members  of a structure can be passed to a function. If a structure is to be passed to a 
called function , we can use any one of the following method. 
Method 1 :­ Individual member of the structure is passed as an actual argument of the 
function call. The actual arguments are treated independently. This method is not suitable 
if a structure is very large structure. 
Method 2:­  Entire structure is passed to the called function. Since the structure declared 
as the argument of the function, it is  local to the function only. The members are valid 
for the function only. Hence if any modification done on any member of the structure , it 
is not reflected in the original structure. 
Method 3 :­  Pointers can be used for passing the structure to a user defined function. 
When the pointers are used , the address of the structure is copied to the function. Hence 
if any modification done on any member of the structure , it is reflected in the original 
structure. 
Return datatype  function name ( structured variable  ) 
Structured Datatype for the structured variable; 

Local Variable declaration; 
Statement 1; 
Statement 2; 
­­­­­­­­­­­­­­ 
­­­­­­­­­­­­­ 
Statement n; 

Example : 
#include <stdio.h> 
struct st 

char name[20]; 
int  no; 
int marks; 
}; 
main( ) 

struct st x ,y; 
int res;

________________________________________________________________________ 
Programming in C Page: ­ 42 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

printf(“\n Enter the First Record”); 
scanf(“%s%d%d”,x.name,&x.no,&x.marks); 
printf(“\n Enter the Second Record”); 
scanf(“%s%d%d”,y.name,&y.no,&y.marks); 
res = compare ( x , y ); 
if (res == 1) printf(“\n First student has got the Highest Marks”); 
else  printf(“\n Second  student has got the Highest Marks”); 

compare ( struct st st1 , struct st st2) 

if (st1.marks > st2. marks  ) return ( 1 ); 
else return ( 0 ); 

In the above example , x and y are the structures sent from the main ( ) function as the 
actual parameter to the formal parameters st1 and st2 of the function compare ( ). 

SCOPE OF VARIABLES OR STORAGE CLASS 

The scope of the variable specifies the part / parts in which the variable is alive. 
Depending on the place of the variable declared , the variables are classified 
into two broad categories as  Global and Local variables.  In some languages like 
BASIC,  all the variables are global and the vales are retained throughout the program. 
But in C language , the availability of value of the variable  depends on the ‘storage ‘ 
class of variable. In C , there are four types of storage classes. They are 

1.  Local  or Automatic variables 
2.  Global or External variables 
3.  Static Variables 
4.  Register Variables. 

1.  Automatic variable: ­ An Automatic variable is a local variable which is declared inside 
the function.  The memory cell is created  at the time of declaration statement 
is executed and is destroyed when the flow comes out of the function. These variables are 
also called as the internal variables. A variable which is declared inside the function without 
using any storage class is assumed as the local variable because the default storage class is 
automatic. 
A variable can be declared automatic explicitly by using the keyword “auto” as 
main ( ) 

auto int x; 

….. 
}

________________________________________________________________________ 
Programming in C Page: ­ 43 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

2.  External  variable: ­ External variable is a global  variable which is declared 
outside the  function.  The memory cell is created  at the time of declaration statement 
is executed and is not destroyed when the flow comes out of the function to go to some other 
function. .The global variables can be accessed by any function in the same program.  A 
global variable can be declared externally in the global variable declaration section. 

int x = 100; 
main ( ) 

….. 
x = 200; 
f1 ( ); 
f2 ( );  … 
….. 

f1 ( ) 

x = x + 1; 
…. 
….. 

f2 ( ) 

x = x + 100; 
…. 
….. 

The variable x is declared above all the functions. It can be accessed by all the 
functions as main( ) , f1 ( ) and f2 ( ). The final value of x is 301. 
3. Static Variables  :  These variables are alive throughout the program. A variable can be 
declared as static by using the keyword “ static ”as 
staic int x ; 
A static variable can be initialized only once at the time of declaration . The initialization part 
is executed only once and retain the value remainder of the program. 
Example Program 
main ( ) 

void f1 ( ); 
f1 ( ); 
f1 ( ); 
f1 ( ); 

void f1 ( )

________________________________________________________________________ 
Programming in C Page: ­ 44 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 


static int x = 0; 
x = x + 1; 
printf(“\n The Value of X is %d “,x ); 

The above program produces the following output 
The Value of X is 1 
The Value of X is 2 
The Value of X is 3. 

4.Register Variables :­ If we want to store the variable in a register instead of memory , the 
variable can be declared as the register variables by using the keyword “register ” as 

register  int x; 

If the variables are stored in the registers , they can be accessed faster than a memory access. 
So the frequently accessed variables can be declared as the register variables. 

Example Program: 

main ( ) 

register x , y z; 
scanf(“%d%d”,&x,&y); 
z=x+y; 
printf(“\n The Output is %d”,z); 

In the above program , all the variables are stored in the registers instead of memory. 

STRUCTURES 

An array is a collection of more than one homogenous elements. The dataitems / 
elements  of the  same type and same length are the homogenous elements. Instead, if we 
want to represent the heterogeneous elements under a single name , we can not use an 
array.  We have to create a structure. A structure is a collection of elements of  different 
datatypes with different lengths. 

To use the structure within a program , we have to create the special datatype,called as 
structured datatype. The general format for defining the structured datatype is

________________________________________________________________________ 
Programming in C Page: ­ 45 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

struct  datatype 

declaring  member1; 
declaring member2; 
­­­­­­­­­­­­­­­­­­­­­­ 
­­­­­­­­­­­­­­­­­­­­­ 
­­­­­­­­­­­­­­­­­­­­­­ 
declaring members; 
}; 

where the members are called as the structure elements. The members may belong to a 
different datatypes. The structured  datatype must be terminated by semicolon.  Since the 
declaration is considered as a single element , the member should be declared 
individually. When the datatype is declared, it is treated as the userdefined datatype 
because it is created by the user.  The declaration is creating a format to represent the 
different members. The format is called as the template. The template is in the form 

struct datatype 

member    1                    respective of the member 1 
Length respective of datatype of member 1 

member 2  Length respective of datatype of 
member 2 

member  3  Length respective of datatype of member 3 

Length respective of datatype of member 4
member 4 

After the datatype is created by the user , a structure variable should be used for 
accessing the member of a structue within a program. To declare a structured variable , 
we have to use the following format in the  declaration part. 
struct  structured datatype variable; 

where the variable is the structured variable (record). 

The structured variable consists of more than one heterogeneous members.To access the 
individual member of a structure , the following format should be used. 

Structured variable.member name 

The operator ‘.’ is called as the dot operator or member operator or period operator. 

________________________________________________________________________ 
Programming in C Page: ­ 46 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Example :­ 
If we want to use the employee records containing the heterogeneous informations  such 
as employee name , employee number , employee salary, we have to do the following 
steps. 

Step 1 :  Creating the  structured datatype. 

struct emp 

char ename[20]; 
int empno; 
float salary; 
}; 

where ename,empno and salary are the hetrogenous members and emp is the structured 
datatype. 

Step 2 : Declare the  structured variable is declared in the declaration part. 

struct  emp employee; 

where employee is the structured variable(record variable). 

Step 3:­  To access the members ename,eno and salary , we can use the formats as 
employee.ename,employee.eno and employee.salary. 

When the structured variable employee is declared , the template is created as 
employee 

ename  respective of the member 1 
20 characters length 

eno  integer 

salary  float

If  the values “RAMA”  , 100 and  25000 are to be given for the members ename eno and 
salary, we use the following statements 

strcpy(employee.name,”RAMA”): 

________________________________________________________________________ 
Programming in C Page: ­ 47 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

employee.eno=100; 
employee.salary=25000; 

Or to ask the value of salary, we use the statement scanf(“%f”,&employee.salary); 

STRUCTURE INITIALIZATION :­ 

Like the other variables , a structured variable can be initialized at the time of  declaration 
of the structured variable using the key word ‘static’.. The general format for structure 
initialization is 

static  structured datatype structured variable = { val1,val2,……,valn}; 

where val1,Val2 ,….,Valn are the values of the members , member 1, member 2 , 
…member n respectively. The values are separated by commas. 

To initialize the structured variable employee with the  values “BALA”,101,25000.00, 
we use the following syntax 

static struct emp  employee  = { “BALA”,101,25000.00}; 

value of the      value of  value of 
member,ename       member eno    member salary 

Note :­ The structured variable can be declared at the time of creating the structured 
datatype. In the above example,   the structured variable is declared as 
struct emp   { 

char ename[20]; 
int empno; 
float salary; 
}employee; 

COMPARISON OF STRUCTURE VARIABLES 

If  rec1 and rec2 are the structure variables having the same datatype, then the following 
operations are valid: 

Operation  Meaning

________________________________________________________________________ 
Programming in C Page: ­ 48 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Assignment operation: 

rec1=rec2;                                                Assigning rec2 to rec1. That is , the member 

values of rec2 are copied to the member values 

of rec1. 

Relational Operation 

r1==r2                                                    returns true if both are equal.That is the 

values of  all the members of  r1 and r2 

are matching. Otherwise, the condition returns 

false. 

r1!=r2                                                      returns true if both are un equal.That is the 

values of  any of the members of  r1 and r2 

are not matching.Otherwise,the condition returns 

false. It is opposite of the previous operation. 

ARRAY OF STRUCTURES : If a  structured variable is created , we can access only 
one structure / record at a particular time. If we want to process more than one records, an 
array of structures is to be created. The array is consisting of structures (records) as the 
elements of it. The general format creating array of structure is 

struct datatype structured variabe [ subscript ]; 

The structures within the array are to be processed in such a way that  processing an 
element in an array. If a structure is to be accessed , the position is to be given as the 
subscript. 
Example:­  Assume that a company has 100 employees. To prepare the payroll for the 
employees , we can use an array of  structures instead of using 100 structure variables as 

struct  emp employee[100];                     // declaration 
It creates an array where each element is a structure as

________________________________________________________________________ 
Programming in C Page: ­ 49 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Employee[0]             employee[1]                 ……………………….  Employee [ 99 ] 
Where each employee structure consists of  empname , empno and salary. 

To read the heterogeneous members , we write the code as 

for (i=0;i<100;i++)scanf(“%s%d%f”,employee[i].name, 
&employee[i].eno,&employee[i].salary); 

Initialization  can be done for  the array of structure as 

static struct emp employee[ ] = 
{“Rama”,100,4500.00,“Bala”,101,6525.00,”Kannan”,102,10000.00}; 

USING ARRAY WITHIN A STUCTURE 
An array may be  made as the member(s) of a structure. To access the member array , we 
have to use the following format 

Structured variable.member[n] 

To access the nth element of the array in the structure where array is one of 
the member in the structure. 

Example: 

To prepare the marklists for 50 students , we use the following code 

struct st 

char  name[20]; 
int rollno; 
float mark[3]; 
}student[50]; 

Where student is an array consists of 50 records. Each record is consisting of the 
members  name 
rollno 
mark[0] 
mark[1] 
mark[2] 
They are internally stored as follows 

Name  rollno  mark[0] mark[1] mark[2]  mark[3 
Name    rollno   mark[0]    mark[1]  mark[2]  Name    rollno   mark[0]    mark[1]  mark[2]

________________________________________________________________________ 
Programming in C Page: ­ 50 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Student [ 0 ]                                           student [ 1 ] 

Name  rollno  mark[0] mark[1] mark[2]  mark[3 
Name    rollno   mark[0]    mark[1]  mark[2] 

Student [ 2 ]                          …. 
….. 

….. 

Name    rollno   mark[0]    mark[1]  mark[2]

Student [ 49 ] 

To access the 3 rd  mark of the 2nd student, we use the structured variable as 
student[1].mark[2]. 

STRUCTURES WITHIN STRUCTURES 

Nesting of structures is also possible in C. That is , a structure may lie within another 
structure as 

struct  stud 


char  ename[20]; 
struct db 

int day; 
char mon[15]; 
int  year; 
}dob; 
int rollno; 

}student; 
To access the member of the inner structure , we use the following format 
struct variable1.structured variable 2 .  member 
Where structured variable1 specifies the outer structure and structured variable is 
specifying the inner structure. Member is the member of inner structure. 
In the above example , student is the outer structure and dob is the inner structure. The 
structure dob is one of the member in it. If we want to access the day of a student , we 
have to use the statement     student.dob.day 

________________________________________________________________________ 
Programming in C Page: ­ 51 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Outer structure   Inner structure   member in the inner structure. 

Note :­ To find the size of a structure , we use the unary operator sizeof as 
Sizeof(struct structured datatype) or sizeof(structure variable). Actually the size of the 
structured variable is the summation of the sizes of the members of the strcture. 

UNIONS 
The concept of Union is borrowed from structures and the formats are also same. The 
distinction between them is in terms of storage. In structures , each member is stored in 
its own location but in Union , all the members are sharing the same location. Though 
Union consists of more than one members , only one member can be used at a particular 
time. The size of the cell allocated for an Union variable depends upon the size of any 
member within Union occupying more no:­ of bytes. The syntax is the same as structures 
but we use the keyword union instead of struct. 
Example:­ the employee record is declared and processed as follows 
union  emp { 
char name[20]; 
int  eno; 
float salary; 
}employee; 

where employee is the union variable which consists of the member name,no and salary. 
The compiler allocates only one cell for the union variable as 
20   Bytes Length

Employee (only one location) 

Location / Cell for name,no and salary 

20 bytes cell can be shared by all the members  because the member name is occupying 
the highest no:­ of bytes. At a particular time we can handle only one member. 
To access the members of an union , we have to use the same format of structures. 

The Unions and Structures are differentiated as follows:­ 

Union  Structures 

________________________________________________________________________ 
Programming in C Page: ­ 52 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

1. It is a collection of heterogeneous                  1. It is also a collection of heterogeneous 
members .  members. 

2.  Though , there are more than one  2. More than one location is reserved. 
Member , only one location is                       For each member , a location is 
reserved.  reserved. 

3.  At a particular time , we can process        3.  At a particular time , we can process 
only one member.                                           more than one members. 

4.   An Union can not be initialized.               4.   A structure can be initialized by using 
static

________________________________________________________________________ 
Programming in C Page: ­ 53 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

FILE MANAGEMENT IN C LANUAGE 

The input and output functions are used for 

(a)  getting the values from the keyboard or from the storage device such as disk. 
(b) displaying values on the screen or writing the values on the storage device 
such as disk. 
The scanf( ) and printf( ) functions are used for doing the input and output using the 
console ( keyboard and Screen).  These methods can be used when the data is small and 
to be kept in the RAM memory. All the information the RAM memory are not 
permanent. They are lost as soon as the power fails or if the user migrates to some other 
programs. Sometimes , we have to use large volume of data and the data are to be saved 
for the later use. In these situations , the files are used.  A file program is a program 
which is used to store the data in the secondary storage device  like a disk  instead of the 
RAM memory because the secondary storage device is the device for storing the 
permanent data.  To perform file operations , there are many built – in functions 
available. 

FILE  BASICS : 
There are basics when we use the file s to keep the information in the disk. They are 

(i) File name  :­ To save the information in the secondary storage device , they must be 
stored under a file name. The file name is a collection of characters. The characters may 
be alphabets  and numeric digits with no special  characters except period ( decimal 
point). The period can be given for the specifying the extension.  The extension is useful 
for categorizing the files. 

(ii) File pointer:­  It is a pointer which points to the address of the data in the file. 
Initially, the file pointer value is NULL since there is no data in the file. When the data is 
written in the file , the file pointer moves to the lastly accessed data. 
(iii) 
(iii) Access methods :­ The file accessing method specifies whether the file data is to be 
accessed sequentially or randomly. 

FILE OPERATIONS 
To write the File program we use the following steps. 

(i)   Declaring the file pointer : ­ 
To use the file in a program , the file pointer has to be set by using the following format 

FILE *file pointer;

________________________________________________________________________ 
Programming in C Page: ­ 54 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

(ii)  Opening a file : ­ 
If we want to perform an operation on a file , the file must be opened. To open a file ,the 
library function  fopen ( ) functions is to be used. 
The general format of the fopen ( )  is 

file pointer = fopen ( file name  enclosed , mode enclosed ); 
in double quotes          in double quotes 

where the mode may be 

r  – Read Mode. The file is opened for reading the data from the file . 

w – Write  Mode. The file is opened for writing the data into the file. 

a  – Append  Mode. The file is opened for appending the data into the file. 
Cases : 
(a) When file is opened in the write mode , the file is opened for writing and deletes 
the already existing data if present. 
(b) When file is opened in the append mode , the file is opened for writing without 
deleting the already existing data if present. 
(c) When file is opened in the read mode , the file is opened for reading if the file is 
present. If the file is not available in the storage device , it produces the error. 

(iii)  Input functions for files : ­ 
For reading the data from the existing data , the output function is used. The input 
functions are  getc ( ) , getw ( ) and fscanf ( ) for inputting  the character  and mixed data 
files respectively. 

a. Character file Input : 

A character file is a file which has the collection of only characters. It is also called as 
the Text file. To read a single character from the file  , the getc ( ) function is to be used 
as 

c = getc ( fp );  // the character read form the file is assigned to c 

where fp is the file pointer. The above function gets a single character from the text file 
and is assigned to c. 

b. Integer file Input : 

An  integer file is a file which has the collection of only integers.  To read a single 
integer from the file  , the getw ( ) function is to be used as 
n = getw ( fp ); // the integer read from the file is assigned to n

________________________________________________________________________ 
Programming in C Page: ­ 55 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

where fp is the file pointer. The above function gets a single integer from the integer file 
and is assigned to n. 

c. Mixed data file Input : 

A  mixed data file is a file which is a collection of mixed data like character and float , 
and integer and structures.  To read the mixed data  from a file  , the fscanf ( ) function is 
to be used as 

fscanf ( file pointer , format specifications ,  & variables ); 
enclosed in double quotes    separated by commas. 

The above function gets a single set of mixed data from the  file. 

Note :­ 
1.  There is no & symbol for the string variable in the fscanf ( ) funcion. 
2.  To do Input file operations ,  the file must be opened in the “read “ mode. 

(iv)  Output functions for files : ­ 
For writing the  data into a file, the output function is used.The output functions for 
character, integer and mixed data files are putc ( ) , putw ( ) and fprintf ( ) respectively. 
Character file Output : 
To write a single character into a  file  , the putc ( ) function is to be used as 

putc (  c  , fp ); 

where fp is the file pointer. The above function write  a single character c into the text 
file. 
Integer file Output : 
To write an integer into a file, the putw ( ) function is to be used as 

putw ( n ,  fp ); 
where fp is the file pointer. The above function write the  single integer n into the  integer 
file. 
Mixed data file Output : 
To write the mixed data  into a  file, the fprintf ( ) function is to be used as 

fprintf ( file pointer , format specifications ,       variables ); 
enclosed in double quotes    separated by commas. 
The above function writes a single set of mixed data into the  file. 

Note :­ 
1.  There is no & symbol for any  variable in the fprintf ( ) funcion.

________________________________________________________________________ 
Programming in C Page: ­ 56 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

2.  To do Output file operations ,  the file must be opened in either  the “read ” 
mode or the “ append ” . 

(v)  Closing a opened file :­ After the operation ( read / write / modify ) is performed 
on a file, the file must be closed. The function fclose ( ) is used to close the file. The 
fclose ( ) has the following format : 

fclose  ( file pointer ); 

Note:­ 
To close more than one files say ‘n’   at a particular time , a singlefunction call 
fcloseall( ) can be used instead of using fclose ( ) ‘n’ times. The function does not have 
argument. 
The format is 
fcloseall ( ); 

Some More Built – in – functions available for doing file operations : 
Some more library functions are available for accessing the files. They are 

(i)  rewind ( ) function :­ It is a function which is used to move the file pointer to the 
beginning of the file. The general form of the rewind ( ) function is 

rewind ( file pointer ); 

(ii)  ftell ( ) function : ­ It returns the current position  of file poinre in terms of bytes. 
The general format of the ftell ( ) function is 
n = ftell ( file pointer ); 
The above function specifies that n bytes have been read already. 

The following statements 

rewind ( f1 ); 
m = ftell ( f1 ); 
printf(“The file pointer is at %d”, m); 

produce the output as 
The file pointer is at 0. 

The file pointer moves to the beginning of the file automatically whenever  a file is 
opened for reading / writing.

________________________________________________________________________ 
Programming in C Page: ­ 57 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

(iii)  fseek ( ) function : ­ This function is used for accessing a file randomly. It is used 
to move the file pointer to the desired position randomly without passing thru 
intermediate positions. The general format of the fseek ( ) function is 
fseek ( file pointer , offset , position ); 

where offset specifies number of positions to be moved from the current location 
position may be 
0  if the move from the beginning of the file 
1  if the file pointer is to be moved from the current position 
2. if the file pointer is to be moved from the end of the file. 

The offset is positive if the file pointer is to moved forward and is negative otherwise. 

Examples:­ 

fseek ( f1 , 4 , 0 );  This function moves the file pointer to the 
5 th  byte in the file from beginning of the file 
( Forward Move ) 

fseek ( f1 , ­ 4 , 2 );  This function moves backward the file 
pointer to the 5 th  byte in the file from the 
end of the file ( Backward Move ) 

fseek ( f1 , ­10  ,10 );  This function moves the file pointer 
backwards  by 10 bytes from the current 
position of file pointer. 

Note :­ When an input function is used to read from the file where the file is opened in 
the read mode,  the functions fetches only one data or a single set of data from the file. So 
to read all the data or set of data from the file, we can use any of the following while 
loops: 

(i) While ( file pointer ! = NULL) 

(ii)  While ( file pointer ! = EOF) 

and      (iii) While ( ! foef( file pointer ) ) 

Program 1 : Assume that there is a Text  file called “Sample” in the disk having two 
paragraphs. Write a Program to copy the first paragraph in a file “sample1” and second 
paragraphs in a file called “sample2” 

/* Program for storing paragraphs nos */ 
# include < stdio. H >

________________________________________________________________________ 
Programming in C Page: ­ 58 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

void main ( ) 

FILE *f1 , * f2 , *f3; 
int n , i , p; 
f1 = fopen (“Sample”, “r”); 
f2 = fopen (“Sample1”, “w”); 
f3 = fopen (“Sample2”, “w”); 

while ( ( c = getc ( f1 ) )! = ‘\ n’) putc ( c , f2 ); 

while (! feof ( f1 ) ) 

c = getc ( f1 ) ; 
putc ( c , f3 ); 

fcloseall( ); 


Program 2 :Assume that there is an integer  file called “Sample” in the disk. Write a 
Program to copy the prime and not prime in two files called as PRIME and NPRIME. 
/* Program for storing prime and Non – prime nos */ 
# include < stdio. H > 
void main ( ) 

FILE *f1 , * f2 , *f3; 
int n , i , p; 
f1 = fopen (“Sample”, “r”); 
f2 = fopen (“PRIME”, “w”); 
f3 = fopen (“NPRIME”, “w”); 
while ( ! feof ( f1 ) ) 

n = getw ( f1 ); 
p = 1; 
for ( i = 2 ; i<= n – 1 ; i + +) 
if ( n % i == 0) p=0; 
if ( p = = 1) putw( n , f2); 
else putw( n , f3); 

fcloseall( ); 
}

________________________________________________________________________ 
Programming in C Page: ­ 59 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

Program 3 :Assume that there is an integer  file called “Text” in the disk. Write a 
Program to take the ‘n’ the character from the file randomly. 

# include < stdio. h > 
void main ( ) 

FILE *f1; 
char str[50]; 
int n , i; 
/*  Creating the file */ 
printf(“\n Enter the string of characters”); 
gets(str); 
f1 = fopen (“Sample”, “w”); 
for ( i = 0 ; i< strlen(st) ­ 1 ; i + +) putc ( st[ i ] , f1); 
fclose(f1); 
f1 = fopen (“Sample”, “r”); 
printf(“\n What is the position of Character  “); 
sanf(“%d”,&n); 
fseek(f1, n – 1 , 0 ); 
printf(“\n The Character is %c”,putc(f1)); 
fclose(f1); 

ERROR HANDLING DURING FILE I/O : 

When the user is doing operations on a file , he / she may face some errors.  The errors 
during file  I/O are called as the exception during file I/O. These errors are handled with 
some built­ in – function. The users have the error during the following events: 

1. Trying to Open a file with a file name which is not present in the storage device. 

2. Attempting to do Write / Append operation on a file which is write protected. On a 
write protected file , only read operation can be done . Writing the new data into the file 
is not valid. 

3. Trying to read after the end of the file is reached. A file ends with end of file. After the 
end of the file , there is no data in the file. 

4. Attempting to perform an operation on a file when a file is opened in some other mode 
like , trying to read if the file is opened in Write / Append mode or trying to write / 
append if the file is opened in read mode 

5. Trying to do an operation without opening the file. Before doing any operation on a 
file, the file must be opened before.

________________________________________________________________________ 
Programming in C Page: ­ 60 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

6. Device overflow – Trying to write some more data on a file when the disk on which 
the file saved is full ( does not have space ). 

The errors are handles by using some built – in – functions as 
(i)  To check whether a file ends or not , we can use any of the following: 
(a)  if  (  foef( file pointer )  )  – True if file ends 
­  False otherwise 

(b)  if ( file pointer == NULL )  – True if file ends 


­  False otherwise 

(ii)  To check whether any error occurs during operations on a file , we can use a 
function called as ferror( ). The function has the following format: 

ferror(  file pointer )  )  – 0 if there is no error 
­  Positive value if error occurs where 
the positive value specifies the error 
code.

________________________________________________________________________ 
Programming in C Page: ­ 61 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

PREPROCESSORS 

As the name suggests , the preprocessors are processed before the compilation is made. In 
a C program , the part which is executed before the compilation done is called as the 
preprocessor. The preprocessors start with #. They are also called as the directives. There 
are different types of directives. The important  directives are 

1.  Macro Substitution directives 
2.  File inclusion directives 
and      3.  Compiler Control directives 

Macro Substitution Directives:­ 

These directives are used for 
(i)  assigning a constant to an identifier 
(ii)  Assigning a symbol to an identifier 
(iii)  assigning an expression to a identifier 
(iv)  assigning a name to a  function 
(v)  declaring a function 
There are three types of macro substitution directives. They are 

(a)  Simple Macro directives :­ The general format of the simple macro directive is 

#define identifer  constant / symbol / fuction 

Examples :­ 
#define ALPHA 1000 
#define LT <= 
#define INPUT scanf 
#define NR ( 45 / 24 ) 

(b)  Argumented Macro directives :­ The general format of the simple macro directive 
is 

#define functions name ( variable )  expression 

Examples :­ 

#define F ( x )     x * x – x – 4              2 


// equivalent to f(x) = x – x ­ 4 

#define SQUARE ( x )    x * x

________________________________________________________________________ 
Programming in C Page: ­ 62 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

#define CUBE ( x )    x * x * x 

(c)  Nested  Macro directives :­ It is used for nesting more than one macros into a single 
macro. 

The general format of the simple macro directive is 

#define functions name ( variable )  expression with already declared
macro 

Examples :­ 

#define FOUR ( x )   (  x *  CUBE ( x ) ) 

#define FIVE ( x )   (  SQUARE( x ) *  CUBE ( x ) ) 

2. File Inclusion Directives :­ 
It is used for linking header file or another C file to the current C File to call the library 
and user defined  function . It has two formats. They are 

Format (i) : 

# include <filename with extension > 
Format (ii) : 

# include “filename with extension ” 

The format (i) is used for  linking the Header file to the current C File. A Header file is a 
file which has the collection of library functions. The format (ii) is used for  linking 
another C file to the current C File where the C file has one or more library functions. 

Examples: 
#include <string.h> 
// to call the string functions 

#include <math.h> 
// To call the mathematical functions 

#include “p2.c” 
// To call one or more user defined functions 
in p2.c in the current C file.

________________________________________________________________________ 
Programming in C Page: ­ 63 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

3. Compiler Control Directives:­ 
These directives are the special directives used for controlling the flow of execution. 
These directives are used for many situations. Some of the  situations are 

(i)  A company has two types of customers as GROUP1 and GROUP2.  A 
procedure code is different for the customers. That means , Code 1 is to be 
used by the GROUP1 and Code 2 is to be used by GROPU2. So a segment 
of the program is to be selected according to the Group. 

(ii)  Assume that a  program has two  different segments ( S1 and S2) . The 
code is to be executed by the system type 1( SYS 1 ) and the other 
segment is to be used by another system type 2 (SYS 2). 

To choose the segment for both the situations , we use a special directive called as 

# ifdef ( GROUP1 / SYS 1 ) 

­­­­­ 

­­­­­­­  Segment  1 

­­­­­­­ 
# else     //  ( GROUP2 / SYS 2 ) 

­­­­­­ 

­­­­­­­ 
#endif 
And in the macro definition , the corresponding group type or system type is to be given 
as 

# define GROUP1 

# define SYS1

________________________________________________________________________ 
Programming in C Page: ­ 64 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

POINTERS 

A  Pointer variable is a variable which is used for storing an address of another variable. 
When the declaration part of a  variable is executed , the compiler allocates a cell to the 
variable in the memory. The size of the variable depends upon the data type of the 
variable.  A memory is a  collection of  more than one cells and each cell has an address. 
To access the variable, we use the name of the variable. When the name is used for 
accessing it , the compiler accesses the variable sequentially. It can be accessed randomly 
if the address of the variable is known. The address of the variable can be stored in the 
pointer variable. 

Example : 

int x = 10 ; when the statement is executed , the 
compiler allocates a cell as 

10 


ADDRESS  50000 

The address of the variable can be stored in variable PX 

10 

ADDRESS  50000 

5000

PX 
ADDRESS  7500 

POINTERS TO FUNCTIONS : 

Like the variables , the function is also stored in the memory and have an address. The 
address of a function can be obtained and can be used for accessing the function. To use 
the pointer to call the function, we have to do the following steps: 

________________________________________________________________________ 
Programming in C Page: ­ 65 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

1.  Declaring a pointer variable to function :­ 
The pointer variable which is to be used for accessing the function is to be 
declared first by using  the format : 

Returned data type   ( * pointer variable ) ( function arguments 
of the function  for  datatypes ) 
which the pointer is used 

2.  Assigning the address to the pointer variable:­ 
After the pointer is declared , the address of the function can be assigned to the 
pointer variable by using the following format: 

Pointer variable = function name without any argument; 

3.  Calling the function:­ 
After the address of the function is assigned to the pointer variable , the following 
format is used for to call the function : 

Pointer variable ( argument list  ); 

Example 1 :­ 

The following program is the example for using a pointer variable for the function 
having no argument: 

# include < stdio.h> 
void main( ) 

void (*ptr) ( );  // Declaring the pointer 
ptr = display;  // Assigning the address of the function to ptr 
ptr ( );  // Calling the function 


void display ( ) 

printf( “\n Hello Welcome”); 

The above program displays the output 

Hello Welcome 

Example 2:­

________________________________________________________________________ 
Programming in C Page: ­ 66 ­ 
St. Mary‛s School of Management Studies
Jeppiaar Educational Trust 

The following program is the example for using a pointer variable for the 
function an argument: 

# include < stdio.h> 
void main( ) 

int fact(int), x; 
int (*ptr) ( int );  // Declaring the pointer 
ptr = fact;  // Assigning the address of the function to ptr 
printf(“\n For what value the factorial is to found?”); 
scanf(“ %d ”, &n); 
x = ptr ( n );  // Calling the function 
printf(“\n Factorial for %d is %d”, n , x); 

display ( int m) 

int  i,n, f = 1; 
for( i = 1 ; i < = m ; i ++) f = f * i; 
return( f ); 

Running the program : 

For what value the factorial is to found? 6 

The above program displays the output 

Factorial for 6 is 720

________________________________________________________________________ 
Programming in C Page: ­ 67 ­ 

You might also like