Recursion in c
Recursion in c
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.
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);