Recursive function

Recursive function


A function which calls itself is called a Recursive function.
Programmer has to be careful while writing a recursive function because if condition is not proper then their are high chances that program will go under an infinite loop.
In recursion, stack concept is used and in stack we have LIFO  principle i.e. function lastly called will be executed first.
Similarly, in program below we called cal() function from main() function and cal() function kept on calling itself until it encountered certain condition.
By default, OS calls main() function.
So, if our program has only one function then that function has to be a main() function.





Program to find factorial using recursion:


#include<stdio.h>
int cal(int);
void main()
{
int n,fact;
printf("Enter number of which you want factorial:");
scanf("%d",&n);
fact=cal(n);
printf("\nFactorial is: %d ",fact);
}
int cal(int x)
{
if(x==0)
return(1);
return (x*cal(x-1));
}

Output:


No comments:

Post a Comment