🔄 Recursion in C with Examples

🔄 Recursion in C Programming

Recursion is a technique where a function calls itself to solve a smaller instance of the same problem. It’s widely used for problems like factorial, Fibonacci, tree traversal, etc.


📘 What is Recursion?

A recursive function is a function that calls itself during its execution. The recursive call helps to break down complex problems into simpler sub-problems.


🧠 Structure of a Recursive Function

  1. Base Case: Condition where the recursion stops.
  2. Recursive Case: Function calls itself with a smaller input.

void recursiveFunction() {
    if (base_condition) {
        return; // base case
    } else {
        recursiveFunction(); // recursive case
    }
}

📌 Example 1: Factorial using Recursion


#include <stdio.h>

int factorial(int n) {
    if (n == 0)
        return 1; // base case
    else
        return n * factorial(n - 1); // recursive call
}

int main() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
    printf("Factorial of %d is %d\n", num, factorial(num));
    return 0;
}

đŸ§Ē Sample Output:

Enter a number: 5
Factorial of 5 is 120

📌 Example 2: Fibonacci Series using Recursion


#include <stdio.h>

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

int main() {
    int i, n;
    printf("Enter the number of terms: ");
    scanf("%d", &n);
    printf("Fibonacci Series: ");
    for(i = 0; i < n; i++) {
        printf("%d ", fibonacci(i));
    }
    return 0;
}

đŸ§Ē Sample Output:

Enter the number of terms: 6
Fibonacci Series: 0 1 1 2 3 5

⚠️ Important Points

  • Every recursive function must have a base case.
  • Without a base case, it leads to infinite recursion (stack overflow).
  • Recursion is memory-intensive due to function call stack.

⚖️ Recursion vs Iteration

Recursion Iteration
Function calls itself Uses loops (for, while)
More memory usage Less memory usage
Elegant and clean code Faster and more efficient

🧩 Practice Problems

  1. Write a recursive function to calculate the sum of first N natural numbers.
  2. Check if a string is a palindrome using recursion.
  3. Find the GCD (Greatest Common Divisor) of two numbers recursively.
  4. Count the number of digits in a number using recursion.

recursion in c, recursive function in c, factorial using recursion, fibonacci using recursion, recursion vs iteration, c programming recursion example, how to write recursive function in c

āĻ•োāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāχ:

āĻāĻ•āϟি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āϟ āĻ•āϰুāύ