C - Recursion



A recursive function in C is a function that calls itself. Recursion is the process of repeating items in a self−similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function. A recursive function is used when a certain problem is defined in terms of itself. Although this involves iteration, using iterative approach to solve such problem can be tedious. Recursive approach provides a very concise solution to seemingly complex problem.

Syntax

void recursive_function(){
   recursion(); /* function calls itself */
}

int main(){
   recursive_function();
}

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 into an infinite loop.

The most popular example of recursion is calculation of factorial. Mathematically factorial is defined as −

 
n! = n X (n-1)!

It can be seen that we use factorial itself to define factorial. Hence this is a fit case to write a recursive function. Let us expand above definition for calculation of 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!
   5 X 4 X 3 X  2 X 1
   = 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. Following is recursive function to calculate factorial.

Non−recursive factorial() function

#include <stdio.h>
#include <math.h>
/* function declaration */
int factorial(int);

int main(){
   int a=5;
   int f = factorial(a);
   printf("a: %d factorial of a: %d", a, f);
}
int factorial(int x){
   int i;
   int f=1;
   for (i=5; i>=1; i--){
      f*=i;
   }
   return f;
}

Output

a: 5 factorial of a: 120

Let us now write a recursive function for calculating the factorial of a given number.

Recursive factorial() function

Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial of a number, generating Fibonacci series, etc.

Example

The following example calculates the factorial of a given number using a recursive function −

#include <stdio.h>
#include <math.h>
/* function declaration */
int factorial(int i){

   if(i <= 1) {
      return 1;
   }
   return i * factorial(i - 1);
}
int  main() {
   int a = 5;
   int f = factorial(a);
   printf("a: %d Factorial of a: %d \n", a, f);
   return 0;
}

Output

a: 5 Factorial of a: 120

When main() calls the factorial() function by passing the variable a, its value is stored in i. The factorial() function successively calls itself. In each call, value of i is multiplied by its earlier value after resucing by 1, till it reaches one. As it reaches 1, the product of all values between the initial value of the argument and 1 is returned to main() function.

Binary search

Let us have a look at another example to understand how recursion works. The problem at hand is to check whether a given number is present in an array.

While we can perform a sequential search for a certain number in the list using a for loop and comparing each number, the sequential search is not efficient especially if the list is too large. The binary search algorithm that checks if the index 'start' is greater than index 'end'. Based on value present at 'mid' variable, the function is called again to search for the element.

We have a list of numbers, arranged in ascending order. The we find the midpoint of the list and restrict the checking to either left or right of midpoint depending on whether the desired number is less than or greater than the number at midpoint.

The following diagram shows how binary search works:

Binary search in c

Example

The following code implements the recursive binary searching technique.

#include <stdio.h>
int bSearch(int array[], int start, int end, int element){
   if (end >= start){
      int mid = start + (end - start )/2;
      if (array[mid] == element)
         return mid;
      if (array[mid] > element)
         return bSearch(array, start, mid-1, element);
         return bSearch(array, mid+1, end, element);
   }
   return -1;
}
int main(void){
   int array[] = {5, 12, 23, 45, 	49, 67, 71, 77, 82};
   int n = 9;
   int element = 67;
   int index = bSearch(array, 0, n-1, element);
   if(index == -1 ) {
      printf("Element not found in the array ");
   }
   else {
      printf("Element found at index : %d",index);
   }
   return 0;
}

Output

Element found at index : 5

Fibonacci Series

In Fibonacci series, a number is the sum of its previous two numbers. To generate Fibonacci series, the ith number is the addition of i−1 and i−2. The following example generates first 10 numbers in the Fibonacci series for a given number using a recursive function −

Example

#include <stdio.h>
int fibonacci(int i){
   if(i == 0) {
      return 0;
   }
   if(i == 1) {
      return 1;
   }
   return fibonacci(i-1) + fibonacci(i-2);
}
int  main() {
   int i;
   for (i = 0; i < 10; i++) {
      printf("%d\t\n", fibonacci(i));
   }
   return 0;
}

Output

When the above code is compiled and executed, it produces the following result −

0	
1	
1	
2	
3	
5	
8	
13	
21	
34

Implementing recursion in a program is difficult for beginners. While any iterative process can be converted in a recursive process, not all cases of recursion can be easily expressed iteratively. A recursive program becomes concise, it is not easily comprehendible. Even if the size of the code may reduce, it needs more resources of the processor, as it involves multiple IO calls to the function.

Recursion is used to perform complex tasks such as tree and graph structure traversal etc. Popular recursive programming solutions include factorial, binary search, tree traversal, tower of Hanoi, eight queens problem in chess etc.

Advertisements