Understanding Recursion in Programming

Recursion is a programming technique where a function calls itself to solve a problem.

Function: A block of reusable code that performs a specific task.
Call itself (Recursion): When a function executes its own code again within its definition.
Problem solving: Breaking down a complex problem into simpler smaller problems.

How Does Recursion Work?

Imagine you want to do a task that can be broken into smaller, similar tasks. The function solves the smaller task by calling itself repeatedly until it reaches a simple case it can solve directly.

Base Case: The simplest instance of the problem which can be solved directly, stopping the recursion.
Recursive Case: The part of the function where it calls itself with a smaller or simpler input.
Stack: Memory structure that keeps track of function calls. Each recursive call adds a new layer to the stack until the base case is reached.

Real Life Example: The Russian Nesting Dolls

Think of Russian nesting dolls (Matryoshka dolls): a big doll contains a smaller doll inside, which contains a smaller doll inside that, and so on, until the smallest doll which has no more dolls inside.

Programming Example: Factorial Function

The factorial of a number n (written as n!) is the product of all positive integers from 1 to n.

Mathematically:

n! = n × (n-1) × (n-2) × ... × 2 × 1

By definition, 0! = 1.

Recursive factorial function in C:

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

Explanation:

Step-by-step for factorial(3):

Another Example: Fibonacci Numbers

The Fibonacci sequence starts as:

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

Each number is the sum of the previous two.

Recursive Fibonacci function in C:

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

Step-by-step for fibonacci(4):

Why Use Recursion?

Important Notes:

Stack Overflow: When the program runs out of memory space to keep track of function calls, often due to infinite recursion.
Divide and Conquer: Algorithm technique where a problem is divided into smaller parts, solved independently, and combined.