C++ Recursion

What is Recursion in C++?

Recursion is when a function calls itself to solve a smaller part of a big problem. It keeps calling itself until it reaches a base case – a stopping point. 🌀

Think of it like Russian nesting dolls – each doll opens up into a smaller one until you hit the tiniest one. 🎯

✅ Why Use Recursion?

  • Helps solve problems that can be broken into smaller sub-problems
  • Great for tasks like factorials, Fibonacci, file directories, etc.
  • Makes code look clean and elegant (sometimes 😄)

📘 Basic Syntax of a Recursive Function

return_type function_name(parameters) {
    if (base_case_condition) {
        return base_value;
    }
    return function_name(smaller_problem); // recursive call
}

🧪 Example: Recursive Countdown

This function prints numbers from 5 to 1 using recursion.

#include <iostream>
using namespace std;

void countdown(int n) {
    if (n == 0) {
        cout << "Lift off!" << endl;
        return;
    }
    cout << n << endl;
    countdown(n - 1);  // recursive call
}

int main() {
    countdown(5);
    return 0;
}
  

Try It Now

🧮 Example: Factorial Using Recursion

Factorial of 5 = 5 × 4 × 3 × 2 × 1

#include <iostream>
using namespace std;

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

int main() {
    cout << "Factorial of 5 is: " << factorial(5) << endl;
    return 0;
}
  

Try It Now

⚠️ Things to Remember

  • Always define a base case – or you’ll get infinite calls!
  • Each recursive call adds to the call stack
  • Too many calls can cause a stack overflow

🔁 Recap

  • Recursion = Function calling itself
  • Needs a base case to stop
  • Useful for problems that repeat in smaller pieces

Recursion feels like magic at first – but once you get it, it’s a superpower! 🧙‍♂️✨