Skip to main content

RECURSIVE FUNCTION


Write a recursive function to calculate the factorial of the number.

When a function call itself or when a function call to a second function and in the function definition of 2nd function again a function call statement for the first function is encountered it is known as recursion and this function is known as recursive function.

Let’s do the program: -

#include<stdio.h>
int factorial (int);
void main()
{
int a,b;
clrscr();
printf("\n enter a no=");
scanf("%d",&a);
b=factorial(a);
printf("\n factorial is =%d",b);
getch();
}
int factorial (int a)
{
if(a==0)
return 1;
else
return(a*factorial(a-1));
}

Dry run: -

a=5 (say)
return
5* factorial (4)
a=4
5*4* factorial (3)
a=3
5*4*3* factorial (2)
a=2
5*4*3*2*factorial (1)
a=1
5*4*3*2*1*factorial (o)
a==0 (true)

return 1

5*4*3*2*1*1= 120
Factorial is = 120.





Comments