Vous êtes sur la page 1sur 19

4 Functions, Structures PIC-17212

Chapter 4: Functions and Structures


4.1 Functions
Need of functions, scope and lifetime of variables, defining functions, function call (call by value, call by
reference), return values, storage classes. Category of function (No argument No return value, No
argument with return value, argument with return value), recursion, Command line arguments (16M)
4.2 Structures
Defining structure, declaring and accessing structure members, initialization of structure, arrays of
structure. (08M)

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.

Function declaration and definition:


In C language to use a variable, first it is declared and then used. Similarly, functions are declared
before using. This declaration is known as prototype of function. The general form for declaring
function is:
return-type function-name(comma separated list of data types for parameters);
e.g.

1
Computer Department, Jamia Polytechnic (0366)
4 Functions, Structures PIC-17212

int square(int);

return type name of function formal parameter


When function is defined, the body of function will be provided. Its general form is as follows:
return-type function-name(parameter list)
{
statement-1;
statement-2; Body of function

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.

Scope and life-time of variables:


Scope of a variable can be defined as the region of program in which the variable can be used.
Scope of variable has two types:
1. Local scope or block scope
2. Global scope or file scope
Variables of local scope can be used within a function or block in which they are declared.
For example, consider two functions, func1( ) and func2( ):
void func1( )
{
int a;
a=10;

}

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

Default initial value: undefined or garbage value.


Scope: local to the block in which the variable is declared.
Life-time: the variable exists in memory as long as the control or flow of execution is within the
block in which it is declared.
e.g.
int main( )
{
int number;

}
or
int main( )
{
auto int number;

}

In the above example, variable number has storage class as auto. The keyword auto is optional.

Register storage class:


The features of variables having register storage class are:
Storage location: CPU registers.
Default initial value: undefined or garbage value.
Scope: local to the block in which the variable is declared.
Life-time: the variable remains in memory as long as the control or flow of execution is within the
block in which it is declared.
A value stored in CPU register can be accessed faster than the value stored in memory. Therefore if a
variable is accessed many times in a program, its storage class should be declared as register. For
example, a variable used as loop counter can be declared as register variable which is shown below:

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

Static storage class:


The features of variables having static storage class are:
Storage location: memory.
Default initial value: zero.
Scope: local to the block in which the variable is declared.
Life-time: the variable remains in memory as long as the program is in execution. The value of
variable is retained between function calls.
Following examples shows that static variable is initialized to zero while a variable with storage
class as auto has garbage value:
# include <stdio.h>
# include <conio.h>
int main()
{
static int i;
auto int j;
clrscr();
printf("i=%d",i);
printf("\nj=%d",j);
getch();
return 0;
}
The output of program is as follows:
i=0
j=-28701
From above example it is clear that if a variable is declared as static in some function, its initial value
will be zero. Similarly the value of static variable is retained between function calls. For example,
after the end of a function if a static variable has value as zero, when the function will be called again
its value will be 100. This value can be further modified by the function if required. Consider
following program:
# include <stdio.h>
# include <conio.h>
int main()
{
void increment(); //function declaration or prototype
clrscr();
increment();
increment();
increment();
getch();
return 0;

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.

External storage class:


The features of a variable with storage class as external are as follows:
Storage location: memory.
Default initial value: zero.
Scope: global (any function can use them).
Life-time: as long as program is executing, global variables exist in memory.
Global variables are declared outside of all the functions. Generally, these are declared above the
first function of any program. Any function can use global variables whenever required. Consider the
following program:
# include <stdio.h>
# include <conio.h>
int i; //i is a global variable
void increment()
{
i++;
printf(i=%d \n,i);
}
int main()
{
clrscr();
printf(i=%d \n,i); //will print i=0
increment(); //will print i=1

7
Computer Department, Jamia Polytechnic (0366)
4 Functions, Structures PIC-17212

increment(); //will print i=2


increment(); //will print i=3
getch();
return 0;
}
The output of the above program will be:
i=0
i=1
i=2
i=3
If a function is using some global variable, then it should be declared with extern keyword in
function. But this is optional as long as the global variable is used within the same source code file.
The above program can be rewritten by using the extern keyword as follows:
# include <stdio.h>
# include <conio.h>
int i; //i is a global variable
void increment()
{
extern int i;
i++;
printf(i=%d \n,i);
}
int main()
{
extern int i;
clrscr();
printf(i=%d \n,i); //will print i=0
increment(); //will print i=1
increment(); //will print i=2
increment(); //will print i=3
getch();
return 0;
}

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.

Example: Function returning a value


# include <stdio.h>
# include <conio.h>
int add(int,int); //function declaration or prototype
int main()
{
int a,b;
int sum;
clrscr();
printf(Enter two numbers: );
scanf(%d%d,&a,&b);
sum=add(a,b);
printf(Addition=%d,sum);
getch();
return 0;
}
int add(int x, int y)
{
return x+y;
}

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:

1) Function with no argument and no return value:


In this category of functions, no arguments are passed to the function. After completing its execution,
it will not return any value. The general form of function declaration will be:
void function_name( );

return type is void, No arguments will be passed to the


therefore function function.
will not return any value
Example: Add two numbers using function:
#include<stdio.h>
#include<conio.h>
int main( )
{
void add( ); //function prototype
clrscr( );
add( ); //function call
getch( );
return 0;
}

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);
}

2) Function with arguments and no return value:


In this category of functions, function will accept parameters(s), but it will not return any value.
Therefore, return type is void. The general form for declaration of such function is:
void function_name( data_type variable1,data_type variable2, );
Following program shows the addition of two values using this category of functions.
#include<stdio.h>
#include<conio.h>
void add(float, float); //function prototype
int main( )
{
float no1, no2;
clrscr( );
printf(Enter any two floating point numbers: );
scanf(%f%f,&no1,&no2);

12
Computer Department, Jamia Polytechnic (0366)
4 Functions, Structures PIC-17212

add(no1,no2); //function call


getch( );
return 0;
}
void add(float f1,float f2)
{
float result;
result=f1+f2;
printf(\nAddition=%f,result);
}

3) Function with no argument and a return value:


In this category of functions, function will not accept any value as parameter, but will return a value.
Therefore in the function return statement will be used. The general form of declaring this type of
functions is as follows:
return_type function_name( );
Following programs shows a function which returns average of two values.
#include<stdio.h>
#include<conio.h>
float average( ); //function prototype
int main( )
{
float avg;
clrscr( );
avg=average( );
printf(Average of value=%f ,avg);
getch( );
return 0;
}
float average( )
{
float a,b;
printf(Enter any two numbers: );
scanf(%f%f,&a,&b);
return (a+b)/2;
}

4) Function with argument and return value:


Functions of this category accept values from caller function as well they return value to the caller
function. The general form for declaring this category of functions is
return_type function_name(data_type variable1, data_type variable2, );

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

2) Following structure stores information about employee:


struct employee
{
int emp_id;
char name[30];
char dept[15];
float salary;
};

3) Following structure stores information about book:


struct book
{
char title[30];
char author[30];
char category[30];
char publisher[30];
float price;
int pages;
};

4) Following structure stores date information:


struct date
{
int day;
int month;
int year;
};

Declaring structure variables and accessing its members:


Structure variables can be declared as follows:
struct structure-name variable-name;
e.g.
struct student s1;
struct employee emp;
struct book pic;
struct date date_of_birth;
To access structure members, following general form is used:

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];
};

Variables of the above structure can be declared and initialized as follows:


struct student s1={1, W. Shakespear, TYEE};
struct student s2={25, J. B. Shaw, FYME};
struct student s3={43, Albert Einstein, FYCO};
Members of structure can be individually accessed and initialized. For example:
struct student s4;
s4.roll_no = 12;
s4.name = B. Gates;
s4.branch = SYCO;
Values can be read using scanf() function and can be assigned to structure members. For example:
struct student s5;
printf(Enter roll number: );
scanf(%d,&s5.roll_no);
printf(Enter student name: );
scanf(%s,s5.name);
printf(Enter branch: );
scanf(%s,s5.branch);

Program: To initialize and print structure variable:


#include<stdio.h>
#include<conio.h>
struct employee
{
int emp_id;
char emp_name[25];
char dept[15];
float salary;
};
int main( )
{
17
Computer Department, Jamia Polytechnic (0366)
4 Functions, Structures PIC-17212

struct employee e = {1024,S. R. Khan,Maintenance,9999.75};


clrscr( );
printf("Employee Id: %d",e.emp_id);
printf("\nEmployee Name: %s",e.emp_name);
printf("\nDepartment: %s",e.dept);
printf("\nSalary: %f",e.salary);
getch( );
return 0;
}

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)

Vous aimerez peut-être aussi