Unit 5 User Defined Functions & Structures
Unit 5 User Defined Functions & Structures
FUNCTIONS:
User‐Defined Functions
To perform any task, we can create function. A function can be called many times. It
provides modularity and code reusability.
Advantage of functions
1) Code Reusability
By creating functions in C, you can call it many times. So we don't need to write the same code
again and again.
2) Code optimization
Example: Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or
not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of
code.
But if you use functions, you need to write the logic only once and you can reuse it several times.
Types of Functions
1. Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(), gets(), puts(), ceil(), floor() etc. You just need to include appropriate
header files to use these functions. These are already declared and defined in C
libraries. oints to be Remembered
System defined functions are implemented in .dll files. (DLL stands for Dynamic Link
Library).
To use system defined functions the respective header file must be included.
2. User-defined functions: are the functions which are created by the C programmer, so
that he/she can use it many times. It reduces complexity of a big program and optimizes
the code. Depending upon the complexity and requirement of the program, you can create
as many user-defined functions as you want.
ELEMENTS OF USER-DEFINED FUNCTINS :
In order to write an efficient user defined function, the programmer must familiar with the
following three elements.
2 : Function Call.
3 : Function Definition
A function declaration is the process of tells the compiler about a function name.
Syntax
return_type function_name(parameter/argument);
return_type function-name();
int add();
Note: At the time of function declaration function must be terminated with ;.
When we call any function control goes to function body and execute entire code.
Syntax : function-name();
function-name(parameter/argument);
Defining a function.
Defining of function is nothing but give body of function that means write logic inside function
body.
Syntax
declaration of variables;
{ {
int z; ( or ) return ( x + y );
z = x + y; }
return z;
When the compiler encounters functionName(); inside the main function, control of the program
jumps to
void functionName()
And, the compiler starts executing the codes inside the user-defined function.
The control of the program jumps to statement next to functionName(); once all the codes inside
the function definition are executed.
Example:
#include<stdio.h>
#include<conio.h>
clrsct();
int a=10,b=20, c;
c=a+b;
void main()
Output
Sum:30
Example:
#include <stdio.h>
int main()
int n1,n2,sum;
scanf("%d %d",&n1,&n2);
return 0;
int result;
result = a+b;
Return Statement
Syntax of return statement
or
For example,
return a;
return (a+b);
The return statement terminates the execution of a function and returns a value to the calling
function. The program control is transferred to the calling function after return statement.
In the above example, the value of variable result is returned to the variable sum in
the main() function.
PARAMETERS :
parameters provides the data communication between the calling function and called function.
2 : Formal parameters.
1 : Actual Parameters : These are the parameters transferred from the calling function (main
program) to the called function (function).
2 : Formal Parameters :These are the parameters transferred into the calling function (main
program) from the called function(function).
Ex : main()
..... .
Where
1 : Actual parameters are used in calling 1 : Formal parameters are used in the
function when a function is invoked. function header of a called function.
Ex : c=add(a,b); Ex : int add(int m,int n);
Here a,b are actual parameters. Here m,n are called formal parameters.
3 : Actual parameters sends values to the 3 : Formal parametes receive values from
formal parameters. the actual parametes.
PASSING PARAMETERS TO FUNCTIONS :There are two ways to pass value or data to
function in C language: call by value and call by reference. Original value is not modified in
call by value but it is modified in call by reference.
The called function receives the information from the calling function through the parameters.
The variables used while invoking the calling function are called actual parameters and the
variables used in the function header of the called function are called formal parameters.
In call by value, value being passed to the function is locally stored by the function parameter in
stack memory location. If you change the value of function parameter, it is changed for the
current function only. It will not change the value of variable inside the caller method such as
main().
Or
When a function is called with actual parameters, the values of actual parameters are copied into
formal parameters. If the values of the formal parametes changes in the function, the values of
the actual parameters are not changed. This way of passing parameters is called pass by value or
call by value.
Ex :
#include<stdio.h>
#include<conio.h>
void main()
int i,j;
scanf("%d%d",&i,&j);
printf("Before swapping:%d%d\n",i,j);
swap(i,j);
printf("After swapping:%d%d\n",i,j);
getch();
int temp;
temp=a;
a=b;
b=temp;
Output
Enter i and j values: 10 20
Before swapping: 10 20
After swapping: 10 20
2 : Pass by reference (OR) Call by Reference : In pass by reference, a function is called with
addresses of actual parameters. In the function header, the formal parameters receive the
addresses of actual parameters. Now the formal parameters do not contain values, instead they
contain addresses. Any variable if it contains an address, it is called a pointer variable. Using
pointer variables, the values of the actual parameters can be changed. This way of passing
parameters is called call by reference or pass by reference.
Ex : #include<stdio.h>
#include<conio.h>
void main()
int i,j;
scanf("%d%d",&i,&j);
printf("Before swapping:%d%d\n",i,j);
swap(&i ,&j);
printf("After swapping:%d%d\n",i,j);
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Output
Before swapping:10 20
After swapping: 20 10
1 : When a function is called the values of 1 : When a function is called the address of
variables are passed variables are passed.
2 : Change of formal parameters in the 2 : The actual parameters are changed since
function will not affect the actual the formal parameters indirectly manipulate
parameters in the calling function. the actual parametes.
3 : Execution is slower since all the values 3 : Execution is faster since only address
have to be copied into formal parameters. are copied.
1 : In this category, there is no data transfer between the calling function and called function.
2 : But there is flow of control from calling function to the called function.
3 : When no parameters are there , the function cannot receive any value from the calling
function.
4: When the function does not return a value, the calling function cannot receive any value from
the called function.
Ex #include<stdio.h>
#include<conio.h>
void sum();
void main()
sum();
getch();
void sum()
int a,b,c;
scanf("%d%d",&a,&b);
c=a+b;
printf("sum=%d",c);
2 : But there is data transfer from called function to the calling function.
3 : When no parameters are there , the function cannot receive any values from the calling
function.
4: When the function returns a value, the calling function receives one value from the called
function.
Ex : #include<stdio.h>
#include<conio.h>
int sum();
void main()
int c;
clrscr();
c=sum();
printf("sum=%d",c);
getch();
int sum()
int a,b,c;
scanf("%d%d",&a,&b);
c=a+b;
return c;
1 : In this category, there is data transfer from the calling function to the called function using
parameters.
2 : But there is no data transfer from called function to the calling function.
3 : When parameters are there , the function can receive any values from the calling function.
4: When the function does not return a value, the calling function cannot receive any value from
the called function.
Ex : #include<stdio.h>
#include<conio.h>
void sum(int a,int b);
void main()
int m,n;
clrscr();
scanf("%d%d",&m,&n);
sum(m,n);
getch();
int c;
c=a+b;
printf("sum=%d",c);
1 : In this category, there is data transfer from the calling function to the called function using
parameters.
2 : But there is no data transfer from called function to the calling function.
3 : When parameters are there , the function can receive any values from the calling function.
4: When the function returns a value, the calling function receive a value from the called
function.
Ex : #include<stdio.h>
#include<conio.h>
int m,n,c;
clrscr();
scanf("%d%d",&m,&n);
c=sum(m,n);
printf("sum=%d",c);
getch();
int c;
c=a+b;
return c;
Inter‐Function Communication
When a function gets executed in the program, the execution control is transferred from calling
function to called function and executes function definition, and finally comes back to the calling
function. In this process, both calling and called functions have to communicate each other to
exchange information. The process of exchanging information between calling and called
functions is called as inter function communication.
Downward Communication
Upward Communication
Bi-directional Communication
Downward Communication
In this type of inter function communication, the data is transferred from calling function to
called function but not from called function to calling function. The functions with parameters
and without return value are considered under downward communication. In the case of
downward communication, the execution control jumps from calling function to called function
along with parameters and executes the function definition,and finally comes back to the calling
function without any return value. For example consider the following program...
Example:
#include <stdio.h>
#include<conio.h>
void main(){
clrscr() ;
num1 = 10 ;
num2 = 20 ;
getch() ;
}
Output
SUM=30
Upward Communication
In this type of inter function communication, the data is transferred from called function to
calling function but not from calling function to called function. The functions without
parameters and with return value are considered under upward communication. In the case of
upward communication, the execution control jumps from calling function to called function
without parameters and executes the function definition, and finally comes back to the calling
function along with a return value. For example consider the following program...
Exmaple:
#include <stdio.h>
#include<conio.h>
void main(){
int result ;
clrscr() ;
getch() ;
num1 = 10;
num2 = 20;
return (num1+num2) ;
Output
SUM=30
Bi - Directional Communication
In this type of inter function communication, the data is transferred from calling function to
called function and also from called function to calling function. The functions with parameters
and with return value are considered under bi-directional communication. In the case of bi-
drectional communication, the execution control jumps from calling function to called function
along with parameters and executes the function definition, and finally comes back to the calling
function along with a return value. For example consider the following program...
Example:
#include <stdio.h>
#include<conio.h>
void main(){
clrscr() ;
num1 = 10 ;
num2 = 20 ;
return (a+b) ;
Output
SUM=30
Standard Functions
The standard functions are built-in functions. In C programming language, the standard functions
are declared in header files and defined in .dll files. In simple words, the standard functions can
be defined as "the ready made functions defined by the system to make coding more easy". The
standard functions are also called as library functions or pre-defined functions.
In C when we use standard functions, we must include the respective header file
using #include statement. For example, the function printf() is defined in header
file stdio.h (Standard Input Output header file). When we use printf() in our program, we must
include stdio.h header file using #include<stdio.h> statement.
C Programming Language provides the following header files with standard functions.
Header
Purpose Example Functions
File
setjump(),
setjmp.h Provides functions that are used in function calls
longjump()
1 : stdio.h
2 : stdlib.h
3 : string.h
4 : math.h
5 : ctype.h
6 : time.h
scanf() int Enter data items from the standard input device.
getchar() int Enter a single character from the standard input device.
fread(s,il,i2,f) int Enter i2 data items, each of size i1 bytes, from file f.
exit(u) void Close all files and buffers, and terminate the program.
floor(d) double Return a value rounded down to the next lower integer.
time(p) long int Return the number of seconds elapsed beyond a designated
base time.
Structure Definition
Structure is a user defined data type which hold or store heterogeneous/different types data item
or element in a single variable. It is a Combination of primitive and derived data type.
or
A structure is a collection of one or more data items of different data types, grouped together
under a single name.
struct keyword is used to define/create a structure. struct define a new data type which is a
collection of different type of data.
Syntax
data_type member1;
data_type member2;
data_type member n;
};
Example
struct employee
{ int id;
char name[50];
float salary;
};
Here, struct is the keyword, employee is the tag name of
structure; id, name and salary are the members or fields of the structure. Let's
understand it by the diagram given below:
We can declare variable for the structure, so that we can access the member of structure easily.
There are two ways to declare structure variable:
1st way:
Let's see the example to declare structure variable by struct keyword. It should be declared
within the main function.
struct employee
{ int id;
char name[50];
float salary;
};
2nd way:
Let's see another way to declare variable at the time of defining structure.
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the
structure variable many times.
If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main()
function.
Structure Initialization
structure variable can also be initialized at compile time.
struct Patient
float height;
int weight;
int age;
};
or
p1.weight = 73;
p1.age = 23;
When the variable is normal type then go for struct to member operator.
When the variable is pointer type then go for pointer to member operator.
structure_variable_name.member_name
Example
struct book
char name[20];
char author[20];
int pages;
};
struct book b1;
Example
struct emp
int id;
char name[36];
int sal;
};
Example of Structure in C
#include<stdio.h>
#include<conio.h>
struct emp
int id;
char name[36];
float sal;
};
void main()
struct emp e;
clrscr();
scanf("%s",&e.name);
scanf("%f",&e.sal);
printf("Id: %d",e.id);
printf("\nName: %s",e.name);
printf("\nSalary: %f",e.sal);
getch();
Output
Id : 05
Name: Spidy
Salary: 45000.00
Example
#include <stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
int main( )
return 0;
Output:
employee 1 id : 101
Nested Structures
structure can have another structure as a member. There are two ways to define nested structure
in c language:
1. By separate structure
2. By Embedded structure
1) Separate structure
We can create 2 structures, but dependent structure should be used inside the main structure as a
member. Let's see the code of nested structure.
struct Date
int dd;
int mm;
int yyyy;
};
struct Employee
int id;
char name[20];
}emp1;
2) Embedded structure
struct Employee
int id;
char name[20];
struct Date
int dd;
int mm;
int yyyy;
}doj;
}emp1;
Accessing Nested Structure
e1.doj.dd
e1.doj.mm
e1.doj.yyyy
Arrays of Structures
Array of structures to store much information of different data types. Each element of the array
representing a structure variable. The array of structures is also known as collection of
structures.
Ex : if you want to handle more records within one structure, we need not specify the number of
structure variable. Simply we can use array of structure variable to store them in one structure
variable.
Example of structure with array that stores information of 5 students and prints it.
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct student{
int rollno;
char name[10];
};
void main(){
int i;
clrscr();
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
getch();
Output:
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz
Student Information List:
Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz
The general format of sending a copy of a structure to the called function is:
Function_name(structure_variable_name);
{
----------
----------
return(exp);
#include <stdio.h>
#include <string.h>
struct student
int id;
char name[20];
float percentage;
};
int main()
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(record);
return 0;
Output
Id is: 1
#include <stdio.h>
#include <string.h>
struct student
int id;
char name[20];
float percentage;
};
int main()
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(&record);
return 0;
#include <stdio.h>
#include <string.h>
struct student
int id;
char name[20];
float percentage;
};
void structure_demo();
int main()
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
structure_demo();
return 0;
void structure_demo()
struct std
int no;
float avg;
};
struct std a;
void main()
{
clrscr();
a.no=12;
a.avg=13.76;
fun(a);
getch();
printf("number is%d\n",p.no);
printf("average is%f\n",p.avg);
#include <stdio.h>
#include <string.h>
struct student
int id;
char name[30];
float percentage;
};
int main()
int i;
ptr = &record1;
return 0;
OUTPUT:
Records of STUDENT1:
Id is: 1
Name is: Raju
Self‐referential Structures
A structure consists of at least a pointer member pointing to the same structure is known as a
self-referential structure. A self referential structure is used to create data structures like linked
lists, stacks, etc. Following is an example of this kind of structure:
A self-referential structure is one of the data structures which refer to the pointer to (points) to
another structure of the same type. For example, a linked list is supposed to be a self-referential
data structure. The next node of a node is being pointed, which is of the same struct type. For
example,
type member1;
type membere2;
: :
: :
typeN memberN;
Ex:
struct emp
int code;