C Recursion

๐Ÿ” C Recursion – Functions Calling Themselves

In C, recursion is a programming technique where a function calls itself to solve a smaller version of the original problem. It’s useful for problems that can be broken down into sub-problems, like factorials, Fibonacci numbers, and more.

๐Ÿ”น Key Concepts of Recursion

  • Every recursive function needs a base case to stop calling itself.
  • Each recursive call should work on a smaller/simpler problem.
  • Too many recursive calls without a base case will cause a stack overflow.

๐Ÿ“ Example 1: Factorial Using Recursion

This function calculates the factorial of a number by calling itself.

#include <stdio.h>

int factorial(int n);

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

int factorial(int n) {
    if (n == 0) {
        return 1; // Base case
    }
    return n * factorial(n - 1); // Recursive call
}
  

Try It Now

๐Ÿ“ Example 2: Fibonacci Series Using Recursion

This function returns the nth Fibonacci number recursively.

#include <stdio.h>

int fibonacci(int n);

int main() {
    int i;
    for (i = 0; i < 10; i++) {
        printf("%d ", fibonacci(i));
    }
    return 0;
}

int fibonacci(int n) {
    if (n == 0) return 0;
    if (n == 1) return 1;
    return fibonacci(n - 1) + fibonacci(n - 2); // Recursive calls
}
  

Try It Now

โš ๏ธ When Not to Use Recursion

  • For very deep or infinite recursion (you may run out of memory).
  • When an iterative solution is simpler and more efficient.

๐ŸŽฏ Summary

  • Recursion = function calling itself with a smaller problem.
  • Always define a clear base case.
  • Commonly used in mathematical problems and data structures.

๐Ÿ’ก Practice Challenge

Try writing your own recursive functions for sum of digits, power calculation, or reverse a number. Recursion is a magical tool once you get the hang of it!