Function and Structure
Function and Structure
A function is a block of code that performs a particular task. There are times when
we need to write a particular block of code for more than once in our program. This
may lead to bugs and irritation for the programmer. C language provides an
approach in which you need to declare and define a group of statements once and
that can be called and used whenever required. This saves both time and space.
function-name
parameters
value
Example :
#include<stdio.h>
int sum(int n1,int n2)
{
return(n1+n2);
}
int main()
{
int num1=11,num2=22;
int result;
result = sum(num1,num2);
printf("\nResult : %d",result);
return(0);
}
Rule 4. Any function can be called from any other function.( main also )
void main( )
{
message( ) ;
}
void message( )
{
printf ( "\nWe are going to call main" ) ;
main( ) ;
}
void message()
{
printf("\nLearning C is very Easy");
}
Rule 6. The order in which the functions are defined in a program and the
order in which they get called need not necessarily be same
void main( )
{
message1( ) ;
message2( ) ;
}
void message2( )
{
printf ( "\n I am First Defined But Called Later " ) ;
}
void message1( )
{
printf ( "\n I am Defined Later But Called First ") ;
}
Rule 8. A function can be called from other function, but a function cannot
be defined in another function.
Example-
main( )
{
printf ( "\nI am in main" ) ;
italy( ) ;
printf ( "\nI am finally back in main" ) ;
}
italy( )
{
printf ( "\nI am in italy" ) ;
brazil( ) ;
printf ( "\nI am back in italy" ) ;
}
brazil( )
{
printf ( "\nI am in brazil" ) ;
argentina( ) ;
}
argentina( )
{
printf ( "\nI am in argentina" ) ;
}
1. User defined functions helps to decompose the large program into small
segments which makes programmer easy to understand, maintain and
debug.
2. If repeated code occurs in a program. Function can be used to include those
codes and execute when needed by calling that function.
3. Programmer working on large project can divide the workload by making
different functions.
TYPES OF FUNCTION
1) Built in(library) functions – these functions are provided by the system and
stored in library , therefore it is called as Library function” example scanf(),
printf(),strlen(),strcpy() etc. To use these functions we need to include
appropriate header file in C program.
2) User defined functions – these functions are defined by the user at the time
of writing the program.
User-defined functions can be categorized as:
1. Function with no arguments and no return value
In this type of functions ,the user defined function does not receive any input
and does not send back any result to the calling function.
Ex:
void msg();
void main()
{
msg();
}
void msg()
{
printf(“hello world\n”);
}
int sum();
void main()
{
int x;
x=sum();
printf(“\n Sum=%d”,x);
}
int sum()
{
int a,b;
scanf(“%d%d”,&a,&b);
return(a+b);
}
In this category of functions, the called function receives one or more input
values, but does not send any output(return value) to the calling function
Ex:
void sum(int,int);
void main()
{
int a,b;
scanf((“%d%d”,&a,&b);
sum(a,b);
}
void sum(int p, int q)
{
int r;
r=a+b;
printf(“sum of two numbers=%d\n”,r);
}
Array Definition :
Array is collection of elements of similar data types .
Passing array to function :
1) The function must be called by passing only the name of the array.
2) In the function definition, the formal parameter must be an array type; the of
the array does not need to be specified.
3) The function prototype must show that the argument is an array.
#include<stdio.h>
#include<conio.h>
//---------------------------------
void fun(int arr[])
{
int i;
for(i=0;i< 5;i++)
arr[i] = arr[i] + 10;
}
//--------------------------------
void main()
{
int arr[5],i;
clrscr();
printf("\nEnter the array elements : ");
for(i=0;i< 5;i++)
scanf("%d",&arr[i]);
for(i=0;i< 5;i++)
printf("\nAfter Function call a[%d] : %d",i,arr[i]);
getch();
}
Output :
for(i=0;i< 5;i++)
fun(arr[i]);
getch();
}
Output :
Enter the array elements : 1 2 3 4 5
Passing array element by element.....
Element : 1
Element : 2
Element : 3
Element : 4
Element : 5
1. This type of scheme in which we are calling the function again and again but
with different array element is too much time consuming. In this
scheme we need to call function by pushing the current status into the
system stack.
2. It is better to pass complete array to the function so that we can save some
system time required for pushing and popping.
Passing Argument to Function :
1. Call by Reference
2. Call by Value
void main()
{
int arr[3] = {1,2,3};
int i;
for(i=0;i<3;i++)
show(arr[i]);
}
void show(int x)
{
printf("%d ",x);
}
#include
void Function(int c[2][2]);
int main(){
int c[2][2],i,j;
printf("Enter 4 numbers:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j){
scanf("%d",&c[i][j]);
}
Function(c); /* passing multi-dimensional array to function */
return 0;
}
void Function(int c[2][2]){
/* Instead to above line, void Function(int c[][2]){ is also valid */
int i,j;
printf("Displaying:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j)
printf("%d\n",c[i][j]);
}
Output
Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5
add(a,b);
Display();
Note :
Display(a,b,c,d,e);
Formal Parameter :
void main()
{
int num1;
display(num1);
}
void display(int x)
{
-----------
-----------
}
x is “Formal Parameter“
Actual Parameter :
void main()
{
int num1;
display(num1);
}
void display(int x)
{
-----------
-----------
}
RECURSION
A function that calls itself is known as recursive function and this technique is
known as recursion.
void recursion()
{
recursion(); /* function calls itself */
}
int main()
{
recursion();
}
Recursion is more elegant and requires few variables which make program clean.
Recursion can be used to replace complex nesting code by dividing the problem into
same problem of its sub-type.
In other hand, it is hard to think the logic of a recursive function. It is also difficult
to debug the code containing recursion.
STRUCTURE
Structure is the collection of variables of different types under a single name for
better handling. For example: You want to store the information about person
about his/her name, citizenship number and salary. You can create these
information separately but, better approach will be collection of these information
under single name because all these information are related to person.
Structure Definition in C
Syntax of structure
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeber;
};
Example of Structure
struct Book
{
char name[15];
int price;
int pages;
};
Here the struct Book declares a structure to hold the details of book which
consists of three data fields, namely name, price and pages. These fields are called
structure elements or members. Each member can have different data type,like
in this case, name is of char type and price is of int type etc. Book is the name of
the structure and is called structure tag.
struct Student
{
char[20] name;
int age;
int rollno;
};
struct Student
{
char[20] name;
int age;
int rollno;
} S1, S2 ;
Here S1 and S2 are variables of structure Student. However this approach is not
much recommended.
struct Book
{
char name[15];
int price;
int pages;
} b1 , b2 ;
We can also use scanf() to give values to structure members through terminal.
Structure Initialization
Like any other data type, structure variable can also be initialized at compile time.
struct Patient
{
float height;
int weight;
int age;
};
There are two types of operators used for accessing members of a structure.
1. Member operator(.)
2. Structure pointer operator(->)Any member of a structure can be accessed
as: structure_variable_name.member_name
Uses of C structures:
Array of Structure
We can also declare an array of structure. Each element of the array representing
a structure variable. Example : struct employee emp[5];
The above code define an array emp of size 5 elements. Each element of array
emp is of type employee
#include< stdio.h>
#include< conio.h>
struct employee
{
char ename[10];
int sal;
};
1 2
Struct dob struct student
{ {
int dd; int rollno;
char month[15]; char name[20];
int yy; struct dob
}; {
struct student int dd;
{ char month[15];
int rollno; int yy;
char name[20]; }d;
struct dob d; }s1;
}s1;
To access the members of student like rollno and name – s1.rollno and s1.name
while to access the members of dob structure s1.d.dd, s1.d.month, s1.d.yy is used.
Example :
#include< stdio.h>
#include< conio.h>
struct student
{
char name[10];
int roll;
};
void show(struct student st);
void main()
{
struct student std;
clrscr();
printf("\nEnter student record\n");
printf("\nstudent name\t");
scanf("%s",std.name);
printf("\nEnter student roll\t");
scanf("%d",&std.roll);
show(std);
getch();
}
Output :
Enter num1 : 10
Enter num2 : 20
Enter num1 : 30
Enter num2 : 40
Enter num1 : 50
Enter num2 : 60
Num1 : 10
Num2 : 20
Num1 : 30
Num2 : 40
Num1 : 50
Num2 : 60
Union
Unions are quite similar to the structures in C. Union is also a derived type as
structure. Union can be defined in same manner as structures just the keyword
used in defining union in union where keyword used in defining structure was
struct.
union car
{
char name[50];
int price;
};
Union variables can be created in similar manner as structure variable.
union car
{
char name[50];
int price;
}c1, c2;
OR;
union car
{
char name[50];
int price;
};
-------Inside Function-----------
union car c1, c2;
In both cases, union variables c1, c2 for type union car is created.