Recursion in C++ - Complete Guide

📚 Core Concepts

What is Recursion?

A function that calls itself to solve a smaller version of the same problem.

Essential Components

  1. Base Case - When to stop (prevents stack overflow)
  2. Recursive Call - Function calling itself with modified parameters
  3. Processing - Optional work done before/after recursive call

Key Points


🔄 Types of Recursion

Type Description Processing Location
Head Recursion Processing before recursive call Above recursive call
Tail Recursion Processing after recursive call Below recursive call

📖 Basic Examples

1. Factorial Calculation

Logic: factorial(n) = n × factorial(n-1)

int getFactorial(int n) {
    // Base case - mandatory
    if(n == 0 || n == 1) {
        return 1;
    }

    // Recursive call - mandatory
    int recursionAns = getFactorial(n-1);
    int finalAns = n * recursionAns;
    return finalAns;
}