UNIT4
UNIT4
UNIT 4
1
UNIT4
DEFINITION OF FUNCTIONS
Defining a function refers to the process of writing the actual code of a
function that performs a specific and identifiable task, such as computing the
factorial of a given number. A function can be defined before or after the main
program. It can be even defined in another file.
A function definition, also known as function implementation includes two
parts, namely,
Function header
Function body.
The general format of a function definition is
Return_type function_name (Argument list with declaration) Function Header
{
local variable declaration;
executable statements;
....................
return statement;
} Function Body
2
UNIT4
The Function Header consists of three parts Return type, Function name and
Argument list with declaration.
i) Return type (also known as function type): It denotes the data type of the
result returned by the function. Return type can be any normal data type
such as int , float, char or void. If the return data type is omitted in the
declaration then the function is assumed to return integer data type. Void
data type is used when the function does not return any value to the
calling function.
ii) Function Name: Function name can be any valid C identifier that is used
to uniquely identify the user defined function.
iii) Argument list with declaration (also known as formal parameters): The
argument list indicates the set of variables that will receive the values
sent by the calling function. Like every other variables, the argument list
should be declared along with their data type.
The Function Body contains the declaration and statements necessary for
performing the required task. The body is enclosed in flower bracket and has
three parts in the order given below.
i). Local variable declaration that specify the variables needed by the function.
These variables are local to the function and are not available outside this
function.
ii). Function statements are the executable statements that are required to
perform the task.
iii). A return statement is used to return the resultant value of the function
to the calling program.
For example consider the following function that is used to find the sum of
two numbers.
3
UNIT4
Returned value
FUNCTION PROTOTYPE
Like variables, all functions in C program must be declared, before they are
invoked. The declaration of a function before using it, is called as a function
prototype. The prototype is used to identify the type of values returned to calling
subprogram and helps the compiler to generate the correct code for the return
data. Prototype can also identify the no.of arguments and the sequence in which
they are used by the function.
The general format of function prototype is as follows:
return_typeFunction_Name (Type1, Type2, ....); or
return_typeFunction_Name( Type1 Arg1, Type2 Arg2, ....);
For example, a function that is used to add two integer numbers and return their
sum can have a typical prototype as
int sum(int, int);
4
UNIT4
OR
int sum( int a, int b);
The argument types in the function declaration must match the types of
parameters in function definition, in number and order. The parameters names do
not need to be same in the prototype declaration and the function definition.
FUNCTION CALL
A function call establishes the link between the called function and the
calling subprogram. A function can be called by specifying its name followed by
a list of actual parameters enclosed in parentheses. General syntax of function
call is as follows.
Variable =Function_Name( arg1, arg2, .....);
When the compiler encounters a function call, the values of actual parameters
are copied to the formal parameters and the control is transferred from the calling
sub program to the called function.
Following points are considered while defining the formal and actual parameters.
The no. of formal parameters should be equal to the no.of actual arguments.
The data types as well as the order of creation of formal parameters and
actual arguments should be same.
The formal parameters and actual arguments can have same or different
names.
5
UNIT4
Return STATEMENT
The return statement is used to send back values from the called function to
the calling function. A function can return none or at most one value per call. The
general form of return statement is,
return;
Or
return (expression);
The first return statement does not return any value to the calling function.
It is used to exit from the function and return the control to the point from where
it is called. The second form returns a single value of the expression to the calling
function.
#include<stdio.h>
6
UNIT4
void main()
{
int m, n, s1;
int sum (int, int); Function Prototype
CATEGORY OF FUNCTIONS
A function, depending on whether arguments are present or not and
whether a value is returned or not, may belong to one of the following categories:
1. Function with no arguments and no return values.
2. Function with no arguments and one return value.
3. Function with arguments and no return value
4. Function with arguments and one return value.
7
UNIT4
from the body of the function as it does not return any value. Finally as these
functions do not return any value, they cannot be used in an expression, instead
they can be only used as an independent statement in the calling function.
Example:
#include<stdio.h>
main()
{ void printline(); /* function prototype */
printline(); /* function call */
printf(“Welcome to c”);
printline();
}
void printline() /* function definition */
{ printf(“--------------------------------------------\n”);
}
In the above example the calling function “main()” calls the function
“printline()”. All the function calls are independent statements and there is no
exchange of data between the called function and calling function.
int sum ( )
{
int s; // Local Variable
s = m+n;
return(s);
}
9
UNIT4
return(s);
}
NESTING OF FUNCTIONS
main( )
{
-------
--------
function1( );
--------
}
function1( )
{
------
function2( );
--------
}
function3( )
{
------
------
}
RECURSION
A function that calls itself directly or indirectly again and again until some specified
condition is satisfied, is termed as a recursive function. Hence the function performs its
specified task by repeatedly calling itself. A recursive function contains a terminating
condition that is used to stop the recursion.
Example: Program to find the factorial of a number using recursion.
#include<stdio.h>
int FACT ( int);
11
UNIT4
void main()
{ int n , fact;
printf(“Enter a number:”);
scanf(“%d”, &n);
fact = FACT(n);
printf(“The factorial of %d is %d”, n, fact);
}
int FACT( int n)
{ if(n == 1)
return (1);
else
return ( n * FACT (n-1));
}
DEFINING A STRUCTURE
The definition of structure starts with a keyword struct, followed by the name of the
structure. All the members of the structure along with their data types are then grouped
together in a flower bracket. Finally, a semicolon is used to terminate the structure definition.
The general format of a structure definition is as follows,
structTag_name
{ data-type Member1;
data-type Member2;
......
data-typeMembern;
};
● Tag_name is the name given to structure during its definition. It identifies the type of
structure with its members. Tag name can be used to subsequently declare structure
variables.
● The Members refers to the data elements of the structure. The list of all structure
members is called as a template. The template informs the compiler about the amount
of memory to reserve for each of structure variable.
For example: A structure to hold students information can be defined as follows,
12
UNIT4
struct student
{ int regno;
char name[15];
float fees;
};
The variable declaration for the above structure can be done as,
struct student S1, S2;
This declaration creates two structure variables S1, and S2 of type student.
It is also possible to combine the structure definition and declaration in one statement as
shown below.
struct student
{ int regno;
char name[15];
float fees;
} S1, S2;
Finally the structure declaration can also be done without using the tag name as follows.
struct
{ intregno;
char name[15];
13
UNIT4
float fees;
} S1, S2;
STRUCTURE INITIALIZATION
Structures can be initialized at compile time by assigning a set of values to each
member of the structure variable during its declaration. The values must be separated by a
comma and enclosed in a flower bracket. As shown below.
For example, the values can be initialized to the above defined structure student as,
struct student S1 = {1234,”Gopal”, 26000 };
14
UNIT4
};
void main()
{
inti;
struct Book B1 = { “Let Us C”, 550, 220.00};
struct Book B2 = {“Let Us C”, 700, 275.00 };
struct Book B3 = B1;
if ( (B1.pages = = B3.pages) && (B1.price == B3.price) )
printf(“ B1 and B3 are same \n”);
else
printf(“B1 and B3 are different \n”);
}
ARRAYS OF STRUCTURES
An array is defined with structure as its data type is called as array of structure. Here
each element of the array is structure. Array of structures are used whenever the same
structure is to be applied to a group of people, items or applications. For example to maintain
the details of all students in a college, we can create a array of structure as follows,
struct student Std[100];
defines an array called std, that contains 100 elements. Each element is defined to be of the
type struct student. Consider the following declaration:
struct Marks
{ int m1;
int m2;
int m3;
};
Marks student[3] = { { 45, 68, 77 }, { 64, 38, 46 }, {57, 36, 71} };
This declares the student as an array of three elements student[0], student[1], and student [2]
and initializes their members as follows: Table of Records
student[0].m1 = 45; m1 m2 m3
student[0].m2 =68;
Student[0]
.......
Student[1]
.......
Student[2]
student[2].m3 = 71;
16
UNIT4
Here, the member subject contains three elements subject[0], subject[1] and subject[2].
These elements can be accessed using appropriate subscripts. For example, the name
Student[1].subject[2];
Would refer to the marks obtained in the third subject by the second student.
Example program:
#include <stdio.h>
struct student
{
Char sname[20];
int marks[3];
}s1;
void main()
{
printf("\nEnter the Name of Student : ");
gets(s1.sname);
2. There may be separate structures. The embedded structure must be defined first
and used as a member of the outer structure. For example,
struct date
{ int day;
int month;
int year;
};
struct student
{ intregno;
char name[20];
struct date dob;
18
UNIT4
};
Note: The embedded structure ’date’ (in case 2) must be defined before the outer structure
‘Student’.
An innermost member in a nested structure can be accessed by chaining all the
concerned structure variable from outer-most to inner-most with the member using dot
operator. For example, to access day month and year from a nested structure we can use the
dot operator as follows;
struct student Mystudent;
/* Accessing the innermost members */
Mystudent.doj.day = 15;
Mystudent.doj.month = 6;
Mystudent.doj.year = 2005;
19
UNIT4
For example:
struct Book
{ char title[20];
float price;
int pages;
};
struct Book Update (struct book); /* Function Prototype */
void main()
{ struct Bok B1={ “Let Us C”, 220.00, 550 };
printf(“The details of book B1 before reprinting\n”);
printf(“Name : %s Price: %.2f Pages: %d\n”,B1.title, B1.price, B1.pages);
B1 = Update(B1); /* Function Call – Passing structure B1 as parameter */
printf(“\nThe details of book B1 after reprinting\n”);
printf(“Name : %s Price: %.2f Pages: %d\n”,B1.title, B1.price, B1.pages);
}
OUTPUT:
20
UNIT4
Structure Array
1. An array is a collection of
1. Structure is a collection of related
related elements of same data
elements of different data types.
type.
Unions
A union is a mutually exclusive collection of elements of which only one should be
used at any given instance of time.
The concept of unions is borrowed from structures and therefore follows the same
syntax as structures. The difference between structures and unions is in terms of storage. In
structures each member has its own storage location; where as all the members of a union
use the same location. So it can handle only one member at a time.
General form of Union definition is as follows:
unionTag_Name
{ data_type Member1;
data_type Member2;
21
UNIT4
......
data_typeMembern;
};
Here union is a keyword, Tag_name is the name that identifies union of this type and
Member1, Member2, ...,Membern are individual members of the union.
unionTag_NameVariable_list;
where variable list is a list of any valid identifier that are separated by comma.
For example:
union Item
{ int m;
Float p;
char c;
};
This defines a union template ‘Item’, to declare the variable of this type we can use the
following statement.
Here a variable of type union having a name ‘purchased’ is created. Union contains
three member of different data type; however only one can exists at a time. The compiler
will allocate a piece of memory that is large enough to hold the largest variable in the union.
In this case it happens to be float variable with 4 bytes. The memory map of the union is as
shown below. 1058 1059 1060 1061 Memory Address
c
Members m
p
To access the union member, we can use the same syntax that we use for structure members.
i.e., purchased.m
purchased.c
while accessing, we should make sure that we are accessing the member whose value is
currently stored.
For example: purchased.m = 500;
22
UNIT4
purchased.p = 12.56;
printf(“ %d”, purchased.m);
would produce erroneous output.
Example: Program to illustrate the unions
union item
{ int m;
float x;
};
OUTPUT:
STRUCTURE UNION
Structure is a collection of related A union is a mutually exclusive collection
items of different data types. of elements of which only one should be
used at any given instance of time.
General form of structure definitions General form of union definitions
structTag_name union Tag_name
{ {
data-type Member1; data-type Member1;
data-type Member2; data-type Member2;
...... ......
}; };
Variable declaration is of the form: Variable declaration is of the form:
structTag_namevariabl-list; union Tag_namevariabl-list;
Size of the structure variable is equal Size of the union variable is equal to the
to the total no.of bytes occupied by largest member size in the union.
23
UNIT4
24