🟡 Control Flow  ·  Lesson 24

Recursion in C++

What is recursion?

Recursion is when a function calls itself. Instead of a loop, the function solves a big problem by handing a slightly smaller version of it to another copy of itself — until the problem is small enough to answer directly.

The base case

Every recursion needs a base case — the simplest input, answered without calling again. It is what stops the chain. The other part, the recursive case, calls the function on a smaller input.

💡 Two parts, always

1) Base case — when to stop. 2) Recursive case — call yourself on something smaller. Miss the base case and it never stops.

Example: factorial

Factorial: 5! = 5 × 4 × 3 × 2 × 1. Notice n! = n × (n-1)! — that is the recursion.

C++
#include <iostream>
using namespace std;

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

int main() {
    cout << factorial(5) << "\n";
    return 0;
}
Output:
120

Tracing the calls

It helps to see how the calls stack up and then unwind:

Trace of factorial(4)
factorial(4) = 4 * factorial(3)
             = 4 * (3 * factorial(2))
             = 4 * (3 * (2 * factorial(1)))
             = 4 * (3 * (2 * 1))
             = 24

The calls go down to the base case, then the answers multiply back up.

Example: Fibonacci

Each Fibonacci number is the sum of the previous two, with two base cases:

C++
int fib(int n) {
    if (n < 2) return n;             // base: fib(0)=0, fib(1)=1
    return fib(n - 1) + fib(n - 2);  // recursive case
}
// fib(6) → 8
💡 Careful

This simple Fibonacci recalculates the same values many times, so it is slow for large n. A loop or memoisation is far faster there.

Recursion vs iteration

RecursionIteration
UsesFunction calls itselfLoops
MemoryExtra (call stack)Less
Best forTrees, divide & conquerCounting, simple repetition

Anything recursive can be written with a loop, and vice versa — pick whichever reads more clearly for the problem.

Common mistakes

  • Forgetting the base case, causing infinite recursion and a stack overflow.
  • A recursive call that does not move toward the base case.
  • Using naive recursion for Fibonacci on large n (very slow).
  • Forgetting to return the recursive call's result.
🏋️ Practice

Write a recursive function to sum numbers from 1 to n, and another to compute the power base^exp. For each, write down the base case first, then the recursive case.

Summary

  • Recursion is a function calling itself on a smaller input.
  • Every recursion needs a base case to stop, plus a recursive case.
  • Factorial and Fibonacci are classic examples.
  • Recursion uses stack memory; a missing base case causes stack overflow.
  • Use recursion for naturally recursive problems; loops for simple repetition.

Frequently Asked Questions

What is recursion in C++?
Recursion is when a function calls itself to solve a problem by breaking it into smaller versions of the same problem. Each call works on a simpler input until it reaches a base case that stops the chain of calls and lets the results unwind back.
What is a base case in recursion?
The base case is the condition that stops a recursive function from calling itself further, giving a direct answer for the simplest input. Without a correct base case the function would call itself endlessly and eventually crash with a stack overflow.
What is the difference between recursion and iteration in C++?
Recursion solves a problem through repeated function calls, while iteration uses loops. Recursion can be more elegant for naturally recursive problems like tree traversal, but it uses extra memory for each call on the stack; iteration is usually more memory-efficient.
What causes a stack overflow in recursion?
A stack overflow happens when recursion goes too deep — often because the base case is missing or never reached — so each call keeps adding a frame to the call stack until it runs out of space and the program crashes.
When should I use recursion in C++?
Recursion suits problems that naturally divide into similar sub-problems, such as factorials, tree and graph traversal, and divide-and-conquer algorithms like merge sort. For simple counting or accumulation, a loop is usually clearer and faster.

Recursion क्या है?

Recursion तब है जब कोई function खुद को call करता है। Loop के बजाय, function एक बड़ी समस्या को उसका थोड़ा छोटा रूप अपनी ही एक और copy को सौंपकर हल करता है — जब तक समस्या इतनी छोटी न हो जाए कि सीधे उत्तर दिया जा सके।

Base case

हर recursion को एक base case चाहिए — सरलतम input, बिना फिर call किए उत्तर दिया गया। यही श्रृंखला रोकता है। दूसरा हिस्सा, recursive case, function को एक छोटे input पर call करता है।

💡 हमेशा दो हिस्से

1) Base case — कब रुकना है। 2) Recursive case — खुद को किसी छोटी चीज़ पर call करना। Base case छूटा तो यह कभी नहीं रुकता।

उदाहरण: factorial

Factorial: 5! = 5 × 4 × 3 × 2 × 1। ध्यान दें n! = n × (n-1)! — यही recursion है।

C++
#include <iostream>
using namespace std;

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

int main() {
    cout << factorial(5) << "\n";
    return 0;
}
Output:
120

Calls को trace करना

यह देखना मददगार है कि calls कैसे जमा होती हैं और फिर समेटती हैं:

factorial(4) का trace
factorial(4) = 4 * factorial(3)
             = 4 * (3 * factorial(2))
             = 4 * (3 * (2 * factorial(1)))
             = 4 * (3 * (2 * 1))
             = 24

Calls base case तक नीचे जाती हैं, फिर उत्तर वापस ऊपर गुणा होते हैं।

उदाहरण: Fibonacci

हर Fibonacci number पिछले दो का योग है, दो base cases के साथ:

C++
int fib(int n) {
    if (n < 2) return n;             // base: fib(0)=0, fib(1)=1
    return fib(n - 1) + fib(n - 2);  // recursive case
}
// fib(6) → 8
💡 सावधान

यह सरल Fibonacci वही values कई बार दोबारा गिनता है, तो बड़े n के लिए धीमा है। वहाँ loop या memoisation कहीं तेज़ है।

Recursion बनाम iteration

RecursionIteration
इस्तेमालFunction खुद को call करता हैLoops
Memoryअतिरिक्त (call stack)कम
किसके लिएTrees, divide & conquerगिनती, सरल दोहराव

कोई भी recursive चीज़ loop से लिखी जा सकती है, और उल्टा भी — जो समस्या के लिए ज़्यादा साफ़ पढ़ा जाए वही चुनें।

आम गलतियाँ

  • Base case भूलना, अनंत recursion और stack overflow पैदा करना।
  • ऐसा recursive call जो base case की ओर न बढ़े।
  • बड़े n पर Fibonacci के लिए naive recursion इस्तेमाल करना (बहुत धीमा)।
  • Recursive call का परिणाम return करना भूलना।
🏋️ अभ्यास

1 से n तक numbers का योग करने को एक recursive function लिखें, और power base^exp निकालने को दूसरा। हर एक के लिए पहले base case लिखें, फिर recursive case।

सारांश

  • Recursion एक function का खुद को छोटे input पर call करना है।
  • हर recursion को रुकने के लिए base case चाहिए, साथ में recursive case।
  • Factorial और Fibonacci classic उदाहरण हैं।
  • Recursion stack memory इस्तेमाल करता है; base case छूटने पर stack overflow होता है।
  • स्वाभाविक रूप से recursive समस्याओं के लिए recursion; सरल दोहराव के लिए loops।
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.