Recursion

Recursive Functions in C++

A recursive function calls itself to solve smaller parts of a problem. Learn the base case, the recursive case, examples in C++ and when to use recursion.

On this page
  1. What a recursive function is
  2. A first example: factorial
  3. Tracing the calls
  4. Why the base case matters
  5. Recursion on linked lists and strings
  6. Recursion versus a loop
  7. Tail recursion
  8. When recursion fits
  9. Common mistakes
  10. Summary

What a recursive function is

A recursive function is a function that calls itself. It solves a problem by reducing it to a smaller version of the same problem, and it stops at a case simple enough to answer directly. That direct answer is the base case. Without one, the calls never end.

Recursion suits problems that break into smaller copies of themselves, such as counting the nodes in a linked list or reversing a string. It is also easy to misuse, so this guide covers both how it works and where it goes wrong.

A first example: factorial

The factorial of a whole number n, written n!, is the product of all the whole numbers from 1 up to n. For example, 5! is 5 × 4 × 3 × 2 × 1, which equals 120. By convention, 0! is 1.

Factorial is a natural fit for recursion, because n! equals n times (n - 1)!. Here is the function in C++:

#include <iostream>

int factorial(int n) {
    if (n <= 1) {                       // base case: return without another call
        return 1;
    }
    return n * factorial(n - 1);        // recursive case: a smaller problem
}

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

The function has two parts. The base case returns a value directly. The recursive case multiplies n by the result of calling factorial with n - 1. The check n <= 1 also covers 0, which is why factorial(0) returns 1 as well. Each call hands a smaller problem to the next call, and the answers come back up the chain.

Tracing the calls

For factorial(3), the calls unfold like this:

  1. factorial(3) needs 3 times factorial(2), so it waits.
  2. factorial(2) needs 2 times factorial(1), so it waits.
  3. factorial(1) meets the base case and returns 1.
  4. factorial(2) finishes with 2 × 1, which is 2.
  5. factorial(3) finishes with 3 × 2, which is 6.

Each call that has not finished yet keeps a frame on the call stack, which holds its parameters and where to return when it is done. Frames are removed as the calls return. Many readers ask what is stack in C with example when they first see this, and the short answer is that the stack is the memory the program uses to track active calls.

Why the base case matters

Many readers ask what is a base case in recursion before they write their first function. The rule is that every starting input must reach the base case, and each call must move closer to it. Here is a function that breaks the rule because it never stops:

void countDown(int n) {
    std::cout << n << "\n";
    countDown(n - 1);   // no base case, so this never finishes
}

Without optimization, each call adds another frame to the call stack. The stack eventually runs out of space, and the program crashes with a stack overflow. On many systems, that crash appears as a segmentation fault, and people often ask what is segmentation fault in c after seeing one. With optimization, a compiler may turn this particular function into an endless loop instead. Either way, the program never finishes.

A base case can also exist and still never be reached. Suppose a function only checks for n == 1 and is called with 0. Then it calls itself with -1, then -2, and so on, and the value 1 is never reached. Checking n <= 1 instead handles both 0 and 1.

Recursion on linked lists and strings

Recursion fits data built from smaller pieces of the same shape. A linked list is a common example, because each node points to the rest of the list. This function counts the nodes:

struct Node {
    int value;
    Node* next;
};

int countNodes(const Node* head) {
    if (head == nullptr) {               // base case: an empty list has no nodes
        return 0;
    }
    return 1 + countNodes(head->next);   // count this node, then the rest
}

Strings work the same way. This function prints a string backward by printing its last character and then recursing on the part before it:

#include <iostream>
#include <string>

void printReversed(const std::string& s, int index) {
    if (index < 0) {                     // base case: every character is printed
        return;
    }
    std::cout << s[index];
    printReversed(s, index - 1);
}

int main() {
    std::string word = "stack";
    printReversed(word, static_cast<int>(word.size()) - 1);  // prints kcats
    return 0;
}

For other ways to reverse text, see how to reverse a string in c.

Recursion versus a loop

Most recursive functions can also be written as loops. The loop version of factorial looks like this:

int factorialLoop(int n) {
    int result = 1;
    for (int i = 2; i <= n; ++i) {
        result *= i;
    }
    return result;
}

Both versions return the same answers. The loop uses one variable and makes no extra calls, so it does not add stack frames. Recursion often reads more clearly when the problem is naturally self-similar, such as walking a tree or splitting a list in halves, as merge sort does. For a simple count like this one, a loop is usually easier to follow and to debug.

Tail recursion

A recursive call is in tail position when it is the last thing the function does. The factorial example above is not tail recursive, because it still has to multiply n after the call returns. Some optimizing compilers can turn a true tail call into a loop, which removes the extra frames. The C++ standard does not require this, so do not count on it for deep recursion.

When recursion fits

Recursion tends to work well when:

  • The problem splits into smaller copies of itself, such as searching a tree or sorting with merge sort.
  • The data is recursive, such as nested folders, linked lists or tree nodes.
  • The recursive definition is clearer than a loop with extra variables.

Be careful, or choose a loop, when:

  • The input can be very large or very deep, because each call uses stack space.
  • The same subproblems are solved again and again. The naive version of Fibonacci repeats the same calls over and over, which makes it slow for larger inputs.

Common mistakes

  • Forgetting the base case, which leads to calls that never end.
  • Writing a base case the input never reaches, such as an off-by-one check.
  • Making the recursive call but forgetting to use its result. For example, factorial(n - 1); on its own multiplies nothing, so the answer is wrong.
  • Recursing very deeply, which can exhaust the stack.
  • Recomputing the same subproblems, which makes naive recursion slow.

Summary

A recursive function calls itself on a smaller version of its problem. Every recursive function needs a base case that returns without another call, and every call must move toward it. Start with a simple example like factorial, trace the calls on paper, and compare with a loop before you choose recursion for a real task.

Keep exploring

Guides from other topics

All topics →

std::optional in C++

std::optional in C++17 holds either a value or nothing. Learn how to check it, read it safely with value_or and return it from a function, with examples.

std::optional 4 min read

NULL vs nullptr in C++

NULL is an older macro, usually defined as 0. nullptr, added in C++11, is a typed null pointer that avoids overload surprises. Here's how to choose.

Is C++ Hard to Learn?

Is C++ hard to learn? This guide explains which parts trip up beginners, how C++ compares with C, and a practical order for learning it step by step.

Is C++ Hard 5 min read