Académique Documents
Professionnel Documents
Culture Documents
Function:
A function is a sub program or set of instructions to perform a specific task. Programs written in C
language may be large and complex. Due to this reason, it is difficult to debug, test and maintain
these large and complex programs. Therefore, programs are divided into smaller sub programs also
called as functions.
Why to use functions / Need of functions:
There are two main reasons to use functions:
1. Using functions avoids rewriting the same code again and again. Suppose in a program there
is a section of code to calculate the area of triangle. If it is needed to calculate the area of
another triangle in the same program, same block of code to calculate area of triangle is
repeated once again. Instead of repeating the code, the previously written code can be reused
by writing it in a function. Hence function avoids repetition of code and it allows reusability.
2. By using functions it becomes easier to write large programs. If a large and complex program
is divided into functions, these functions can be developed by different programmers in
parallel. This will reduce program development time. Also, it becomes easier to locate and
debug programming errors. Testing and maintenance of smaller functions is also easier as
compared to larger programs.
1
Computer Department, Jamia Polytechnic (0366)
4 Functions, Structures PIC-17212
int square(int);
statement-n;
}
For example, the function square( ) declared earlier can be defined as follows:
int square(int n) function declarator
{ function definition
return n*n; function body
}
First line of function definition is called function declarator. This is similar to function declaration
except that it has parameter names and it is not terminated by semicolon. Parameter list is optional.
The function declarator is followed by function body which consists of the statements that will be
executed when function is called. These statements are closed in braces { }. In the declaration and
declarator of functions, you must use the same function name, number of parameters, parameter
types, and the return value. No function definition is allowed within a function definition.
Function call:
A function call is made by writing function name followed by the values of parameters enclosed in
parenthesis (brackets). e.g. if there is a function having name square that accepts integer value as
parameter and returns the square of the value, then we can call the function anywhere in program as
follows:
int num=10;
int sq=0;
sq=square(num);
If function returns a value, as in the above example, we can store the return value in a variable which
is of same data type as that of return value.
In the above example, the return value of the function is stored in a variable sq.
2
Computer Department, Jamia Polytechnic (0366)
4 Functions, Structures PIC-17212
The parameters used in function call are known as actual parameters or arguments.
void func2( )
{
int b;
b=10;
}
In the above example, variable a is local to func1( ), therefore, it cannot be used in func2( ).
Similarly, variable b is local variable declared in func2( ). It can be used only in func2( ).
Local variables are created when function in which they declared is called. After the execution of
completed, these local variables are destroyed.
The variables having global scope can be used anywhere in the program. These are declared outside
of all the functions. Every function of the program can use global variables as and when required.
Consider the following example:
int a;
int main( )
{
a=10;
}
void func1( )
{
3
Computer Department, Jamia Polytechnic (0366)
4 Functions, Structures PIC-17212
a=a+1;
}
void func2( )
{
a=100;
}
In the above example, variable a is declared outside of all the functions, therefore, it has global
scope. Since it has global scope, any function can use it. In the above example, variable a is used
by three functions: main( ), func1( ) and func2( ).
Global variables are available as long as program is in execution. These are created when program
starts execution and destroyed when program execution is over.
Life-time of the variable is the time period during which memory is allocated to them. Life-time of
local variables is the period while the block in which these variables are declared is in execution.
Similarly life-time of global variables the period during which the program is in execution.
Storage classes:
All the variables used in a program have their own storage class. Storage class gives the information
such as:
1) where the variable will be stored in system
2) what will be default initial value of variable if the initial value is not used
3) what is the scope of the variable
4) what is the life-time of variable.
There are four storage classes in C:
a) Automatic storage class
b) Register storage class
c) Static storage class
d) External storage class
Automatic storage class:
All the variables declared within a function have automatic storage class. The features of these
variables are:
Storage location: memory.
4
Computer Department, Jamia Polytechnic (0366)
4 Functions, Structures PIC-17212
In the above example, variable number has storage class as auto. The keyword auto is optional.
int main( )
{
register int i;
for(i=1; i<=10;i++)
printf(\n%d,i);
return 0;
}
5
Computer Department, Jamia Polytechnic (0366)
4 Functions, Structures PIC-17212
6
Computer Department, Jamia Polytechnic (0366)
4 Functions, Structures PIC-17212
}
void increment() //function definition
{
static int i=100;
printf(i=%d \n,i);
i++;
}
The output of the above program will be:
i=100
i=101
i=102
This is because i is declared as static. Initially its value will be 100 because it is initialized with this
value. The last statement of function is to increment the value of variable by 1. It will become 101,
which is printed after 100. Again the value of i is incremented by 1 and it becomes 102 which is
printed when the function increment( ) is called third time.
7
Computer Department, Jamia Polytechnic (0366)
4 Functions, Structures PIC-17212
Return values:
A function can return a value. This value is returned to the calling function. The value which is
returned by the function can be used as per the requirement in the calling function.
The function which returns value, requires to use the return statement. The general form of return
statement is:
return;
8
Computer Department, Jamia Polytechnic (0366)
4 Functions, Structures PIC-17212
or
return (expression);
The expression can be a constant, a variable, user-defined structure, general expression or a function
call. e.g.
return 10;
return factorial;
return a+b;
return emp1; etc.
Call by value:
Using parameters, values can be passed from calling function to called function. In C language,
there are two mechanisms to pass arguments or parameters to functions: pass arguments by value
which is known as call by value method, and pass arguments by address or pointer also known as
call by reference method.
In call by value, actual parameters are copied into formal parameters. Actual parameters are those
which are used in function call. Formal parameters are the parameters used in function definition.
Thus when call by value is used, function operates on copy of actual parameters. Due to this, if
9
Computer Department, Jamia Polytechnic (0366)
4 Functions, Structures PIC-17212
parameter values are changed in the called function, there is no effect on parameters of calling
function (i.e. actual parameters) and their value remains unchanged. Following program illustrates
this:
# include <stdio.h>
# include <conio.h>
void swap(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
int main()
{
int i,j;
clrscr();
printf(Enter two integer numbers: );
scanf(%d%d,&i,&j);
printf(Before swapping i=%d, j=%d,i,j);
swap(i,j);
printf(\nAfter swapping i=%d, j=%d,i,j);
getch();
return 0;
}
The output of program is shown below:
Enter two integer numbers: 3 7
Before swapping i=3, j=7
After swapping i=3, j=7
As shown in the output, values of actual parameters are not changed because the function swap( )
operated on copy of actual values.
Call by Reference:
At the time of call, instead of passing values, if addresses of parameters are passed it is called call
by reference. Address of a variable can be accessed by using & operator. e.g. if i is some
variable, its address is accessed by using &i statement.
Following program uses call by reference. In call by reference, if value of formal parameter is
changed the value of actual parameter also gets changed.
10
Computer Department, Jamia Polytechnic (0366)
4 Functions, Structures PIC-17212
# include <stdio.h>
# include <conio.h>
void increment(int *ptr)
{
*ptr=(*ptr)+1;
}
int main()
{
int i=10;
clrscr();
printf(Value of i before increment: %d,i);
increment(&i);
printf(Value of i after increment: %d,i);
getch();
return 0;
}
The output of the program will be:
Category of functions:
There are four categories of function:
11
Computer Department, Jamia Polytechnic (0366)
4 Functions, Structures PIC-17212
void add( )
{
int a, b;
int sum;
printf(Enter any two integer numbers: );
scanf(%d%d,&a,&b);
sum=a+b;
printf(\nsum=%d,sum);
}
Example: Area of circle using function:
#include<stdio.h>
#include<conio.h>
void area( ); //function prototype
int main( )
{
clrscr( );
area( ); //function call
getch( );
return 0;
}
void area( )
{
float radius, area;
printf(Enter radius of circle: );
scanf(%f,&radius);
area=(22.0/7)*radius*radius;
printf(\nArea of circle=%f,area);
}
12
Computer Department, Jamia Polytechnic (0366)
4 Functions, Structures PIC-17212
13
Computer Department, Jamia Polytechnic (0366)
4 Functions, Structures PIC-17212
Following example shows a function that accepts one integer value as argument and returns its
square.
#include<stdio.h>
#include<conio.h>
int square(int); //function prototype
int main( )
{
int num, sq;
clrscr( );
printf(Enter a number: );
scanf(%d,&num);
sq=square(num);
printf(Square of the number=%d: ,sq);
getch( );
return 0;
}
int square(int a)
{
return a*a;
}
Recursion:
In C language, functions can call themselves. A function is known as recursive if a statement
within the body of the function calls the same function. Recursion is the process of defining
something in terms of itself. While using recursive functions, there must be some criterion to stop the
execution of function, otherwise the function will never stop.
Following example shows a recursive function to calculate factorial of a given number:
#include<stdio.h>
#include<conio.h>
int factorial(int); //function prototype
int main( )
{
int num, fact;
clrscr( );
printf("Enter a number: ");
scanf("%d",&num);
fact=factorial(num);
printf("Factorial of %d=%d ",num,fact);
getch( );
return 0;
}
int factorial (int a)
14
Computer Department, Jamia Polytechnic (0366)
4 Functions, Structures PIC-17212
{
int f;
if(a==0)
return 1;
else
{
f=a*factorial(a-1);
return f;
}
}
Structures:
Structure groups variables into a single entity. If we want to store single value at a time, simple data
types such as int, float, char, double can be used. But in real world, there are objects for which we
have to store more than one value for each and every object to describe its attributes or properties.
e.g. a book has a title, author name, category, price, publisher and possibly ISBN etc. There may be
thousands of books. If we will use different variables for each and every object property, it becomes
very difficult to manage the information. Using structures, we can create derived data type. A
structure contains a number of basic data types grouped together. These data types may or may not
be same.
Defining structures:
The general form for defining structures is:
struct structure-name
{
data-type variable-1;
data-type variable-2;
data-type variable-3;
data-type variable-n;
};
For example:
1) Following structure defines a structure student:
struct student
{
int roll_no;
char name[25];
char branch[4];
};
15
Computer Department, Jamia Polytechnic (0366)
4 Functions, Structures PIC-17212
structure-variable . structure-member
e.g.
s1.roll_no=10;
16
Computer Department, Jamia Polytechnic (0366)
4 Functions, Structures PIC-17212
emp.salary=27625.0;
Initializing structure members:
Structure variables can be initialized by using following notation:
struct structure-name variable-name = {value-1, value-2, , value-n};
Suppose a structure student is defined as follows:
struct student
{
int roll_no;
char name[25];
char branch[4];
};
Array of structures:
Array is a collection of similar type elements. Structures store information about some particular
object. If there are more than objects, array of structures can be used. the array elements are stored in
continuous locations in memory.
The array of structures can be declared as follows:
struct structure-name array-name[size];
Suppose there is a structure book to store information about books as follows:
struct book
{
char title[30];
char author[30];
char category[30];
char publisher[30];
float price;
int pages;
};
To create an array of above structure with size 10, following statement can be used:
struct book arr[10];
The elements of this array are arr[0], arr[1], arr[2], , arr[9]. For loop or while loop can be used to
read and print values stored in structure members.
Following program uses structure array to store book information and calculates average book price:
#include<stdio.h>
#include<conio.h>
struct book
{
char title[30];
char author[30];
int price;
};
struct book arr[5]; //array of structures declared
18
Computer Department, Jamia Polytechnic (0366)
4 Functions, Structures PIC-17212
int main( )
{
int i;
float sum, average;
clrscr( );
printf("Enter book information:\n);
printf("---------------------------------------------------\n ");
for(i=0;i<5;i++)
{
printf("Enter title: ");
scanf("%s",arr[i].title);
printf("Enter author name: ");
scanf("%s",arr[i].author);
printf("Enter price: ");
scanf("%d",&arr[i].price);
printf("---------------------------------------------------\n ");
}
sum=0;
for(i=0;i<5;i++)
{
sum=sum+arr[i].price;
}
average=sum/5.0;
printf("\nAverage price of books: %f",average);
getch( );
return 0;
}
End of Chapter 4
19
Computer Department, Jamia Polytechnic (0366)