Recursion in C

Recursion in C. Recursion in C Tutorial. Learn Recursion in C
Recursion in C

What is Recursion in C?

Recursion in C refers to a function calling itself again and again until a certain condition is met. It is a powerful technique used in programming to solve complex problems that can be broken down into smaller subproblems.

Recursion is used when a problem can be divided into smaller subproblems of the same type. The advantage of using recursion is that it makes the code more concise and easier to read. Recursion is particularly useful when working with tree-like data structures.

What is Recursive Function in C?

A recursive function in C is a function that calls itself one or more times within its own body. This technique is commonly used when working with complex data structures or when solving problems that can be broken down into smaller subproblems.

The process of memory allocation in recursion involves the creation of a new stack frame for each recursive call. Each stack frame contains a copy of the function’s local variables, as well as the return address and any parameters that were passed to the function. When the function returns, the stack frame is deallocated, and the program continues executing from the point where the function was called.

Examples of Recursive Function

Example 1: Factorial of a number

#include<stdio.h>
int factorial(int n){
   if(n==1)
      return 1;
   else
      return n * factorial(n-1);
}
int main(){
   int num = 5;
   printf("Factorial of %d is %d", num, factorial(num));
   return 0;
}

Output:

Factorial of 5 is 120

Explanation:

In above example, the factorial function calls itself repeatedly until it reaches the base case of n=1. Then, it returns the final result of the factorial.

Example 2: Fibonacci series

#include<stdio.h>
int fibonacci(int n){
   if(n==0)
      return 0;
   else if(n==1)
      return 1;
   else
      return fibonacci(n-1) + fibonacci(n-2);
}
int main(){
   int num = 7;
   printf("Fibonacci series up to %d terms:\n", num);
   for(int i=0; i<num; i++)
      printf("%d ", fibonacci(i));
   return 0;
}

Output:

Fibonacci series up to 7 terms: 0 1 1 2 3 5 8

In above example, the fibonacci function calls itself repeatedly to generate the Fibonacci series up to the specified number of terms.

Rules to follow while using Recursion in C:

  1. Always define a base case for the recursion to prevent infinite looping.
  2. Make sure that the function’s input parameters are updated correctly for each recursive call.
  3. Avoid using recursion for problems that can be solved more efficiently with a loop.
  4. Be aware of the potential for stack overflow when using recursion with large data sets.

More: