What is Recursion in C explained with example?
Recursion is a programming technique where a function calls itself again and again in order to solve a problem. In C, recursion is implemented by having a function call itself, directly or indirectly. Each time a recursive function is called, a new set of variables is created, and the function starts executing again from the beginning. When the base case is reached, the function stops calling itself and starts returning the values up the chain of function calls.
Here is an example of a recursive function in C that calculates the factorial of a given number:
#include<stdio.h>
int factorial(int);
int main()
{
int no,ans;
printf("Enter Any Number");
scanf("%d",&no);
ans=factorial(no);
printf("factorial=%d",ans);
return 0;
}
int factorial(int n)
{
if (n == 0)
{
return 1;
}
else
{
return n * factorial(n-1);
}
}
In this example, the function "factorial" takes an integer "no" as input and calculates its factorial value. The function has a base case of no=0, where it returns 1, and for no>0 it returns n* factorial(n-1).
When the function is called with no=4, it will call itself with no=3, then no=2, no=1, no=0 and at each step, the recursive call is made and the value is returned to the previous call and the final value is returned to the main function.
The function call stack for no=4 will look like this: factorial(4) factorial(3) factorial(2) factorial(1) factorial(0)
Here, the function call factorial(0) is the base case where the recursion ends and the final value is returned as 4*3*2*1=24
Recursion can also be used to solve problems like Fibonacci series, Tower of Hanoi, etc. It's a powerful technique but it should be used carefully as it can lead to stack overflow errors if the function calls itself too many times without reaching the base case.