what is recursion in c explain with example
Answers
Answered by
2
Recursion is a common method of simplifying a problem into subproblems of same type. This is called divide and conquer technique. A basic example of recursion is factorial function.
Example:
int factorial(int n){
if(n==0) return 1;
else return (n* factorial(n-1));
}
In above factorial example : factorial function calles itself by multiplying n with factorial of n-1 and stops when it reaches to the bas condition at fact 0 by returning 1.
So function calling done in the following way.
fact(5).
5*fact(4) //calls fact(4)
5*4*fact(3)
5*4*3*fact(2)
5*4*3*2*fact(1)
5*4*3*2*1*fact(0)
5*4*3*2*1*1 // stops here
Example:
int factorial(int n){
if(n==0) return 1;
else return (n* factorial(n-1));
}
In above factorial example : factorial function calles itself by multiplying n with factorial of n-1 and stops when it reaches to the bas condition at fact 0 by returning 1.
So function calling done in the following way.
fact(5).
5*fact(4) //calls fact(4)
5*4*fact(3)
5*4*3*fact(2)
5*4*3*2*fact(1)
5*4*3*2*1*fact(0)
5*4*3*2*1*1 // stops here
Similar questions