C Recursive Function

In general recursion means the process of repeating items in a self-similar way. Similarly in programming language, when a function calls itself, then it is known as recursive function and this technique is known as recursion. For example :
void recursiveFunc() {
  ...  ..  ...
  recursiveFunc();
  ...  ..  ...
}

int main() {
  ...  ..  ...
  recursiveFunc();
  ...  ..  ...
}
At above example recursiveFunc() is a recursive function, we can see that the function recursiveFunc() is called from the main() function, and inside the recursiveFunc() block, the function called itself.


The recursive functions can be effectively used to solve problems where solution is expressed in terms of successively applying the same solution to subsets of the problem. For example we can solve many mathematical problems, such as calculating the factorial of a number, generating fibonacci series, etc. Also remember that while writing recursive functions, the programmers need to be careful to define an exit condition from the function, otherwise it will go into an infinite loop.

Now lets see some example of recursive function.

The following example generates the fibonacci series for a given number using a recursive function :
include <stdio.h>

int fibonacci(int);

int main() {
  int c = 10, x;

  for(x = 0; x < c; x++) {
    printf("%d, ", fibonacci(x));
  }

  printf("\n");
  return 0;
}

int fibonacci(int n) {
  if(n == 0) {
    return 0;
  }

  if(n == 1) {
    return 1;
  }

  return fibonacci(n-1) + fibonacci(n-2);
}
Output :

0, 1, 1, 2, 3, 5, 8, 13, 21, 34

The following example calculates the factorial of a given number using a recursive function :
#include <stdio.h>

unsigned long int factorial(unsigned int);

int main() {
  int num = 10;
  printf("factorial of %d is %ld\n", num, factorial(num));
  return 0;
}

unsigned long int factorial(unsigned int x) {
  if(x <= 1) {
    return 1;
  }
  return x * factorial(x - 1);
}
Output :

factorial of 10 is 3628800


Next Topic: