Recursion in C Language


Recursion in C Language

àRecursion is a process by which a function calls itself repeatedly, until some specified condition has been satisfied.

àThe process is used for repetitive computations in which each action is stated in terms of a precious result.

àIn order to solve a problem recursively, two conditions must be satisfied.

àThe problem must be written in a recursive form, and the problem statement must include a stopping condition.

àThe best example of recursion is calculation of factorial of an integer quantity, in which the same procedure is repeating itself.

Example:

Write a C Program to calculate factorial of a given number using recursion.
#include <stdio.h>
main()
{
int number;
long int fact(int number);
printf(“Enter number”);
scanf(“%d”, & number);
printf(“Factorial of number is % d\n”, fact(number));
}
long int fact(int number)
{
if(number <=1)
return(1);
else
return(number *fact(number-1));
}

The point to be noted here is that the function ‘fact’ calls itself recursively, with an actual argument (n-1) that decrease in value for each successive call.
The recursive calls terminate the value of the actual argument becomes equal to 1. When a recursive program is executed, the recursive function calls are not executed immediately.

Followers