Recursion
1
INTRODUCTION
Recursion is the process by which a function calls itself.
C language allows writing of such functions which call itself to solve
complicated problems by breaking them down into simple and easy
problems. These functions are known as recursive functions.
What is a Recursive Function in C?
A recursive function in C is a function that calls itself.
A recursive function is used when a certain problem is defined in terms
of itself.
Although it involves iteration, using iterative approach to solve such
problems can be tedious.
Recursive approach provides a very concise solution to seemingly
complex problems.
2
Factorial Using Recursion
Recursive functions are very useful to solve many mathematical problems such as
calculating the factorial of a number, generating Fibonacci series, etc.
The most popular example of recursion is calculation of factorial. Mathematically, a
factorial is defined as −
n! = n X (n-1)!
Let us expand the above definition for calculating the factorial value of 5.
5! = 5 X 4!
5 X 4 X 3!
5 X 4 X 3 X 2!
5 X 4 X 3 X 2 X 1!
5X4X3X 2X1
= 120
While we can perform this calculation using a loop, its recursive function involves
successively calling it by decrementing the number till it reaches 1
3
Non-Recursive Factorial
Function
#include <stdio.h>
int factorial(int); // function declaration
int main( )
{
int a = 5, f; OUTPUT
f = factorial(a); //function call
printf("a: %d \n", a); a: 5
printf("Factorial of a: %d", f); Factorial of a: 120
}
int factorial(int x) //function definition
{
int i;
int f = 1;
for (i = 5; i >= 1; i--){
f *= i;
}
return f;
}
4
Recursive Factorial Function
#include <stdio.h>
int factorial(int);
int main(){
int a = 5,f;
f = factorial(a);
printf("a: %d \n", a);
printf("Factorial of a: %d", f);
return 0;
}
int factorial(int i)
{
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1);
}