Recursion
Recursion

 

  • In the C programming language a recursive function is a special function that calls to itself in a program . Like other programming languages, C language allows you to define recursive functions easily in program .
  • The C programming language supports recursion, i.e., a function to call itself. But while using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go in infinite loop.
  • A C recursive function allows you to break down a complex problem into identical sub-problems recursively until the sub-problems are simple enough to solved directly in c language. The solutions are then combined to produce the solution to the original problem. This is a famous programming technique called divide and conquer in c language .
  • In c language , A C recursive function must have at least one exit condition that must be satisfied a program . Otherwise, the C recursive function will call itself indefinitely until a stack overflow error is occurs.
  • Recursive function are very useful to solve many mathematical problems like to calculate factorial of a number, generating Fibonacci series, etc.

Advantages and Disadvantages of Recursion

  • Recursion is more elegant and requires few variables which make program clean. Recursion can be used to replace complex nesting code by dividing the problem into same problem of its sub-type.
  • In other hand, it is hard to think the logic of a recursive function. It is also difficult to debug the code containing recursion.

 

Example : Recursive function for factorial

1#include<stdio.h>
2#include<conio.h>
3int fact(int);
4int main()
5{
6   int num,f;
7   printf(“\nEnter a positive number: “);
8   scanf(“%d”,&num);
9   f=fact(num);
10   printf(“\nFactorial of %d is: %d”,num,f);
11   return 0;
12}
13int fact(int n)
14{
15   if(n==1)
16      return 1;
17   else
18      return(n*fact(n-1));
19}

 

Output :
Enter a positive number: 5
Factorial of 5 is: 120