Recursion in C language is the process of calling same function from itself. Recursion is like a loop, that call itself, so to exit from the recursion process we need to define the exit condition.
Syntax of recursion
return_type function_name (args..)
{
statements;
...
..
function_name(args..);
}
Example
void myFunction()
{
myFunction();
}
int main()
{
myFunction();
}
Program to find factorial of number using recursion
#include<stdio.h>
unsigned long long fact(int x)
{
if(x <= 1 )
return 1;
return x*fact(x-1);
}
int main()
{
int a = 5;
printf("Factorial of 5 is %llu\n", fact(a));
return 0;
}
Output
Factorial of 5 is 120
Program to find the power of function using recursion
#include<stdio.h>
unsigned long long power(int x, int y)
{
if(y == 1)
return x;
return x*power(x, y-1);
}
int main()
{
int a = 8, b=2;
printf("%d power %d is %llu\n", a, b, power(a, b));
return 0;
}
output
8 power 2 is 64