Recursion in C | Programs of recursion in c

Preview
You must first complete Types of function in C Language before viewing this Lesson

Recursion in C

Function repeatedly calling itself is called recursion. But we need to specify some condition to stop execution of recursive function otherwise function may run infinite.



 Program using recursion to find factorial of a number .
#include<stdio.h>
int fact(int no)
{
if(n0==1||n0==0)
return(1);
else
return(no*fact(no-1));
}
int main()
{
int f1,n;
printf(“\nEnter a number”);
scanf(“%d”,&n);
f1=fact(n);
printf(“\nFactorial of %d=%d”,n,f1);
return(0);
}
Output
Enter a number=4
Factorial of 4 =24
Description

Function fact() check whether value of parameter no is equal to 1 or 0.  In case of 1 or 0, factorial will be returned as 1 otherwise statement  no*fact(no-1) will execute.

Suppose value of n is 4, execution will be as follows:

f = 4* fact (3); will be evaluated. This statement again calls fact() function with value n-1 which will return value

4*fact(4-1);

This process continues until value of no is equal to 1 or 0 and when no is equal to 1 it returns 1 and execution of this function stops. Process  is as f0llows

f1 = 4* fact (3-1);

f1 =4*3* fact (3-1);

f4 = 4*3*2*fact (2-1);

f 1= 4*3*2*1;

f = 24;





Nesting of functions in C

It is the process in which a function calls another function.

 Program for nesting of function.
#include<stdio.h>
void msg()
{
printf(”\nHello”);
}
void disp()
{
printf(”Welcome”);
msg();       /*Function msg() nested within function show().*/
}
int main()
{
disp();
return(0);
}
Output
Welcome
Hello

Best Books of C





Lesson tags: conditions of recursion, nesting of function in c, procedure of recursion in c, program to find factorial of a number using recursion in c, program to print fibonacci series using recursion in c, recursion in c
Back to: C Programming Language