Skip to content
    SeaCode
    Learning tracksCode ArenaWorkshops & EventsInstructors
    Log inSign up
    C++C++

    C++ fundamentals

    • Your first C++ program
    • Variables and types
    • Operators and input
    • Conditions: if and switch
    • Loops

    Functions and collections

    • Functions
    • References: by value or by reference?
    • Strings and arrays
    • std::vector
    • map, set and unordered_map

    Memory and pointers

    • Pointers
    • Stack, heap, new and delete
    • Smart pointers and RAII

    Classes and OOP

    • struct and class
    • Constructors and destructors
    • Inheritance and virtual functions
    • Templates

    The STL and professional C++

    • Algorithms and lambdas
    • Exceptions
    • Recursion
    • Project: a grade book
    C++

    The STL and professional C++ · Lesson 20 of 21

    Recursion

    A function calling itself: the base case, the call stack, and memoization.

    10 minutes2 games

    Recursion solves a problem by having a function call itself on a smaller version of the same problem. It needs two things:

    1. A base case: a small case answered directly, without recursing. 2. A step that shrinks the problem toward the base case.

    C++
    #include <iostream>
    #include <string>
    
    long long factorial(int n) {
        if (n <= 1) return 1;            // base case
        return n * factorial(n - 1);     // smaller problem
    }
    
    int digitSum(int n) {
        if (n < 10) return n;
        return n % 10 + digitSum(n / 10);
    }
    
    bool isPalindrome(const std::string& s, int i, int j) {
        if (i >= j) return true;
        return s[i] == s[j] && isPalindrome(s, i + 1, j - 1);
    }
    
    int main() {
        std::cout << factorial(5) << " " << factorial(20) << "\n";
        std::cout << digitSum(9045) << "\n";
        std::string w = "level";
        std::cout << isPalindrome(w, 0, static_cast<int>(w.size()) - 1) << "\n";
        return 0;
    }
    Step by step1 / 8
    1. ▶factorial(4)
    2. 2 4 * factorial(3)
    3. 3 3 * factorial(2)
    4. 4 2 * factorial(1)
    5. 5 return 1
    6. 6 return 2 * 1 = 2
    7. 7 return 3 * 2 = 6
    8. 8 return 4 * 6 = 24

    Variables

    stackf(4)

    Output

    …

    Each call waits for the one inside it. That's the call stack: it fills on the way down and empties on the way back.

    Memoization: never compute the same thing twice

    C++
    #include <iostream>
    #include <unordered_map>
    
    long long calls = 0;
    
    long long fibSlow(int n) {
        calls++;
        if (n < 2) return n;
        return fibSlow(n - 1) + fibSlow(n - 2);
    }
    
    std::unordered_map<int, long long> memo;
    long long fibFast(int n) {
        calls++;
        if (n < 2) return n;
        auto it = memo.find(n);
        if (it != memo.end()) return it->second;
        return memo[n] = fibFast(n - 1) + fibFast(n - 2);
    }
    
    int main() {
        calls = 0;
        std::cout << fibSlow(30) << " in " << calls << " calls\n";
        calls = 0;
        std::cout << fibFast(30) << " in " << calls << " calls\n";
        return 0;
    }

    Important

    Each call takes stack space. Forget the base case, or go very deep (say, recursing over a million-element list), and you get a stack overflow crash. Then switch to a loop, or manage your own stack (std::vector).

    Spot the bug

    This function overflows the stack for any positive number. Where's the problem?

    Interview question

    When is recursion better than a loop? What is memoization?

    Exercise

    Write int power(int base, int exp) recursively (no loops, no pow), and print power(2, 10) and power(3, 4) on two lines.

    Expected output:
    1024
    81
    C++
    #include <iostream>
    
    int power(int base, int exp) {
        
    }
    
    int main() {
        std::cout << power(2, 10) << "\n";
        std::cout << power(3, 4) << "\n";
        return 0;
    }

    Learn more from

    • learncpp: Recursionlearncpp.com
    • Wikipedia: Memoizationen.wikipedia.org
    • Wikipedia: Recursion (computer science)en.wikipedia.org

    Played 0 of 2 games

    Sign in to save your progress and earn XP.

    PreviousExceptionsNextProject: a grade book
    SeaCode

    Learn to code for real, online or at our branch in front of Cairo University, Giza.

    Learn

    • All courses
    • Interactive tutorials
    • Interview practice problems
    • Mock interview
    • Learning tracks
    • Code Arena
    • Workshops & Events
    • Knowledge library
    • Team projects

    Your account

    • Log in
    • Sign up
    • Learning plan
    • Certificates
    • Site map

    Contact us

    • WhatsApp
    • 010 9094 1104
    • In front of Cairo University, Giza

    © 2026 SeaCode. All rights reserved.