Function
Function
A function is a block of code that performs a specific task. Every C program has at
least one function, which is main(), and all the most trivial programs can define
additional functions.
Types of function
1. Standard library function
2. User defined function
To use the above library function we have to include corresponding header file using
pre-processor directive i.e #include.
A function that is declare, calling and define by the user is called user define
function. Here logic is provided by user. Every user define function has three parts
as:
For writing a function name , the rules are same as the rules for writing a variable
name.
User defined function is always written outside the main function i.e above the main
function or below the main function, but to use that function we have to give
reference of that function in the main function. Giving reference is called function
call.
Each function is having its own functionalities . To use one function someone has to
call it. Ex.TV has different functionalities. Remote has also different functionalities,
but they do not work on their own. We use them by pressing keys. So without
function call we can’t use its functionalities.
Example:
#include<stdio.h>
int sum(int,int); //Function declaration
void main()
{
int a=10,b=20,s;
s=sum(a,b); // Function Call
printf(“sum is %d”,s);
}
int sum(intx,int y) // Function Defination
{
returnx+y;
}
Calling function need information about called function .If called function is place
before calling function then the declaration is not needed. The argument list in the
function definition as well as function declaration must be matched.
Syntax :
return_typefunction_name (type1 arg1 , type2 arg2);
OR
return_typefunction_name (type1, type2);
Function Call
A function is called by simply writing its name followed by the argument list inside the
parenthesis.
Syntax:
function_name(arg1,arg2..);
Example:
void main() //Calling function
{
x();
printf(“Hello”);
y();
}
x() //Called function
{
printf(“welcome”);
}
y()
{
printf(“How are you”);
}
Output:
Welcome
Hello
How are you
Note: A function can be called from other function but a function can’t be defined in
another function.
Function Definition
3. Local variable declared inside the function is local to that function. It cannot be
used anywhere in the program and its existence is only within the function. Function
declaration outside the main function is called global declaration. Such a function
can be be accessed by all function in program. Function declaration inside the main
function is called local declaration and it is accessed by only main().
5. Return type denote the type of value that function will return and return type is
optional if omitted it is assumed to be integer by default.
In C we can do both declaration and definition at same place and at that time no
semicolon is used,
It can be written as constant , function expression on any function call which return a
value .
ex: funct (6,9) , funct ( a,b )
Formal Arguments:
1. Arguments which are mentioned in function definition are called dummy or formal
argument.
2. These arguments are used to just hold the value that is sent by calling function.
3. Formal arguments are like other local variables of the function which are created
when function call starts and destroyed when end function.
c) Where other local variables are assigned variable through the statement inside the
function body.
Note: Order, number and type of actual argument in the function call should be
matched with the order , number and type of formal arguments in the function
definition .
Function Categories
There are four main categories of the functions these are as follows:
Example:
void link (void) ;
void main ()
{
link ();
}
void link ( void )
{
printf (“ link the file “)
}
1. call by value
2. call by reference
1. Here the copy of actual arguments is passed to the formal arguments and
operation is done in the formal argument.
2. Since formal arguments are photo copy of actual argument, any change of the
formal arguments does not affect the actual arguments. Memory occupied by
actual arguments and formal arguments are different. So Only changes are made
in the memory location occupied by formal parameters.
3. Changes made to the formal argument t are local to block of called function, so
when control back to calling function changes made vanish.
4. .
Example:
void swap (int a , int b) /* called function */
{
int t;
t = a;
a=b;
b = t;
printf(“value of a & b is %d%d”,a,b);
}
main( )
{
int k = 50,m= 25;
swap( k, m) ; / * calling function */
printf(“after swapping in calling function %d %d”,k,m);
}
Output:
Value of a & b is 25 50
After swapping in calling function 50 25
Explanation:
int k= 50, m=25 ;
Means first two memory space are created k and m , store the values 50 and 25
respectively.
swap (k,m);
When this function is calling the control goes to the called function.
void swap (int a , int b),
k and m values are assigned to the ‘a’ and ‘b’.
then a= 50 and b= 25 ,
After that control enters into the function a temporary memory space ‘t’ is created
when int t is executed.
t=a; Means the value of a is assigned to the t , then t= 50.
a=b; Here value of b is assigned to the a , then a= 25;
b=t; Again t value is assigned to the b , then b= 50;
after this control again enters into the main function and execute the printf(k,m). it
returns the value 50 , 25.
NOTE:
Whatever change made in called function not affects the values in calling function.
Call by reference method
Example:
‘&’ symbol is used for getting the address. ‘*’ is used for getting the value from
corresponding address. int * a means value at address of a.
NOTE:
In call by address mechanism whatever change made in called function affect the
values in calling function
Here you will learn to pass the array (both 1D or multi dimensional arrays) to a
function in C programming with some examples.
Before passing the entire array element, let’s see how you can pass individual
elements of an array to a function.
Passing array elements to a function is similar to passing variables to a function.
Example 1:Passing an array
printf(“%d”,a1);
printf(“%d”,a2);
}
void main()
{
intarr[]={5,20,45,33,16};
display(arr[1].arr[4]); //passing 2nd and 5th element to display()
}
Output: 20 16
Example 2: Passing arrays to a function
inti;
float x=0.0;
for(i=0;i<5;i++)
x=x+mark[i];
return x;
}
void display(intarr[2][2]);
void main()
{
intarr[2][2],i,j;
printf(“enter 4 numbers\n”);
for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf(“%d%d”,&arr[i][j]);
display(arr); //Passing 2D array to the function
}
void display(intarr[2][2])
{
intx,y;
printf(“Displaying:\n”);
for (x=0;x<2;x++)
for(y=0;y<2;y++)
printf(“%d\n”,arr[x][y]);
}
Output: enter 4 numbers:
2
5
7
9
Displaying:
2
5
7
9
NOTE:In C prog.,you can pass arrays to functions, however you can’t return array
from functions.
Example 4: Display a string using function
char a[6]=”Hello”;
display(a); //Passing string as an argument to function
}
Output: Hello
Recursion
fun();
statements
}
void fun()
{
statements
void main()
{
int a;
printf(“Enter a number”);
scanf(“%d”,&a);
fun(a);
}
int fun(int b)
{
printf(“%d”,b);
b--;
if(b>=1) /* Termination condition i.e. b is less than 1*/
{
fun(b);
}
}
How control flows in successive recursive calls?
Flow of control in successive recursive calls can be demonstrated in following
example:
Consider the following program which uses recursive function to compute the
factorial of a number.
int fact(int);
void main()
{
intn,f;
printf(“Enter a number”);
scanf(“%d”,&n);
f=fact(n);
printf(“Factorial of %d is %d”,n,f);
}
int fact(int m)
{
int a;
if (m==1)
return 1;
else
a=m*fact(m-1);
return a;
}
In the above program if the value entered by the user is 1 i.e.n=1, then the value of n
is copied into m. Since the value of m is 1 the condition ‘if (m==1)’ is satisfied and
hence 1 is returned through return statement i.e. factorial of 1 is 1.
When the number entered is 2 i.e. n=2, the value of n is copied into m. Then in
function fact(), the condition ‘if(m==1)’ fails so we encounter the statement
a=m*fact(m-1); and here we meet rcursion. Since the value of m is 2 the expression
(m*fact(m-1)) is evaluated to (2*fact(1)) and the result is stored in a(factorial of a).
Since value returned by fact(1) is 1 so the above expression reduced to (2*1) or
simply 2. Thus the expression m*fact(m-1) is evaluated to 2 and stored in a and
returned to main(). Where it will print ‘Factorial of 2 is 2’.
In the above program if n=4 then main() will call fact(4) and fact(4) will send back the
computed value i.e. f to main(). But before sending back to main() fact(4) will call
fact(4-1) i.e. fact(3) and wait for a value to be returned by fact(3). Similarly fact(3) will
call fact(2) and so on. This series of calls continues until m becomes 1 and fact(1) is
called, which returns a value which is so called as termination condition. So we can
now say what happened for n=4 is as follows
fact(4) returns (4*fact(3) )
fact(3) returns (3*fact(2) )
fact(2) returns (2*fact(1) )
fact(1) returns (1)
So for n=4, the factorial of 4 is evaluated to 4*3*2*1=24.
For n=3, the control flow of the program is as follows:
From main()
To main()
Implementation of Recursion
We came to know that recursive calls execute like normal function calls, so there is
no extra technique to implement recursion. All function calls(Whether Recursive or
Non-Recursive) are implemented through run time stack. Stack is a Last In First
Out(LIFO) data structure. This means that the last item to be stored on the
stack(PUSH Operation) is the first one which will be deleted(POP Operation) from
the stack. Stack stores Activation Record(AR) of function during run time. Here we
will take the example of function fact() in the previous recursive program to find
factorial of a number.
Suppose fact() is called from main() with argument 3 i.e.
fact(3); /*From main()*/
Now will see how the run time stack changes during the evaluation of factorial of 3.
The following steps will reveal how the above stack contents were expressed:
First main() is called, so PUSH AR of main() into the stack. Then main() calls fact(3)
so PUSH AR of fact(3). Now fact(3) calls fact(2) so PUSH AR of fact(2) into the
stack. Likewise PUSH AR of fact(1). After the above when fact(1) is completed, POP
AR of fact(1), Similarly after completion of a specific function POP its corresponding
AR. So when main() is completed POP AR of main(). Now stack is empty.
In the winding phase the stack content increases as new Activation Records(AR) are
created and pushed into the stack for each invocation of the function. In the
unwinding phase the Activation Records are popped from the stack in LIFO order till
the original call returns.
Examples of Recursion
Q1. Write a program using recursion to find the summation of numbers from 1 to n.
Ans: We can say ‘sum of numbers from 1 to n can be represented as sum of
numbers from 1 to n-1 plus n’ i.e.
Sum of numbers from 1 to n = n + Sum of numbers from 1 to n-1
= n + n-1 + Sum of numbers from 1 to n-2
= n+ n-1 + n-2 + ................ +1
The program which implements the above logic is as follows:
#include<stdio.h>
int sum(int);
void main()
{
intn,s;
printf(“Enter a number”);
scanf(“%d”,&n);
s=sum(n);
printf(“Sum of numbers from 1 to %d is %d”,n,s);
}
int sum(int m)
{
int r;
if(m==1)
return (1);
else
r=m+sum(m-1); /*Recursive Call*/
return r;
}
Output:
Enter a number 5
15
#include<stdio.h>
int power(int,int);
void main()
{
intn,m,k;
printf(“Enter the value of n and m”);
scanf(“%d%d”,&n,&m);
k=power(n,m);
printf(“The value of nmfor n=%d and m=%d is %d”,n,m,k);
}
int power(int x, int y)
{
if(y==0)
{
return 1;
}
else
{
return(x*power(x,y-1));
}
}
Output:
Enter the value of n and m
3
5
The value of nmfor n=3 and m=5 is 243
Q3:Write a program to print Fibonacci Series upto a given number of terms.
Ans:
Fibonacci series is a sequence of integers in which the first two integers are 1 and
from third integer onwards each integer is the sum of previous two integers of the
sequence i.e.
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ……..........................
The program which implements the above logic is as follows:
#include<stdio.h>
int Fibonacci(int);
void main()
{
intterm,i;
printf(“Enter the number of terms of Fibonacci Series which is going to be printed”);
scanf(“%d”,&term);
for(i=0;i<term;i++)
{
printf(“%d”,Fibonacci(i));
}
}
int Fibonacci(int x)
{
if(x==0 || x==1) return 1;
else
return (Fibonacci(x-1) + Fibonacci(x-2));
}
Output:
Enter the number of terms of Fibonacci Series which is going to be printed 6
1 1 2 3 5 8 13
Exercise