Loading...

C++ Recursion

The scope page ended with forty-eight lines on the screen, and the last one was 2, the print of count after mark_local. This page starts from that screen, in the same file types.cpp, and the first box still holds the word pine. The announce, show_label, scale, and mark_local functions stay above main. This page continues the Functions module. The new work adds a function that calls itself. Each call prints one number, then asks for a smaller number, until a stop condition ends the chain. After the earlier ending lines, main starts that chain once. The screen grows to fifty-one lines, and the last one is 1.
Recursion is a function that calls itself with a smaller problem. The self-call is an ordinary call written with the same function name. Without a stop, the chain never ends. With a stop, each call does a little work and then either returns or calls again with a nearer stop. This page uses a countdown so you can see the chain on the screen as three clear lines.
Programs use recursion when a problem shrinks into the same shape of problem. A countdown is the smallest clear shape: print the current number, then count down from one less. The workshop loops and the earlier function prints stay above the new lines, so the new 3, 2, and 1 sit at the end of the screen where you can count them after the scope ending.

Above main, after mark_local, sits void down(int n). Inside its braces, the first check is the stop: if (n <= 0) { return; }. When n is already 0 or less, the function prints nothing and returns. When n is still positive, the next line prints it: std::cout << n << std::endl;. Then the function calls itself with a smaller argument: down(n - 1);.
Inside main, after the print of count, the file calls down(3);. That one call starts the chain. The first body prints 3, then calls down(2). That body prints 2, then calls down(1). That body prints 1, then calls down(0). The stop returns without printing. Control unwinds back through the finished calls and returns to main.
Walk the new ending. The lines through 9 and 2 from the scope page stay. Then down(3); adds 3, then 2, then 1. The last three new lines are 3, then 2, then 1. There are fifty-one lines in all, and the last one is 1. Each call had its own parameter box named n, which is why scope still matters: three stacked calls can each hold a different n at the same time.

If the stop were missing, every call would print and call again forever, and the program would not finish. That failed experiment stays in the prose, not in the checked file. The checked file always moves toward zero by calling down(n - 1).
A while that counts down also prints 3, then 2, then 1, but it stays inside one function body and changes one local box. Recursion reaches the same three lines by stacking calls. This page keeps the print above the self-call so the screen counts down. If you moved the print below the self-call, the order of lines would change; keep the print first for the countdown shown here.
A common mistake is to call down(n) again with the same n, so the stop never gets closer. Another common mistake is to forget the stop and watch the program hang. A third mistake is to think recursion replaces scope; each call still gets its own locals and parameters while the call stack grows.
This page stops before the next module, where you begin building types with fields. The next page names that tool once at the end. Recursion here only shows the self-call, the smaller argument, and the stop.

Type the file in this order, or add only the new lines if types.cpp is already on disk. Above int main(), keep the earlier functions, and add down with the stop, the print of n, and the self-call down(n - 1). Near the end of main, after the print of count and before return 0;, add down(3);. The file name on disk stays types.cpp. The checked file is below, and the new lines are the down definition and that one call in main.

types.cpp adds down that prints then calls itself until the stop

cpp
#include <iostream>
#include <string>

void announce()
{
    std::cout << "call" << std::endl;
}

void show_label(std::string label)
{
    std::cout << label << std::endl;
}

int scale(int n)
{
    return n * 2;
}

int scale(int n, int factor)
{
    return n * factor;
}

void mark_local()
{
    int local = 9;
    std::cout << local << std::endl;
}

void down(int n)
{
    if (n <= 0) {
        return;
    }
    std::cout << n << std::endl;
    down(n - 1);
}

int main()
{
    // the word stays pine
    std::string word = "pine";
    int count = 2;
    double ratio = 0.5;
    bool ready = true;
    double price = 7.9;
    const int limit = 10;
    int scores[3] = {4, 5, 6};
    std::string other = "cone";
    std::string joined = word + " " + other;
    int total = 17;
    int step = 3;
    step += 4;
    int score = 72;
    int goal = 50;
    bool wet = false;
    std::string result;
    int day = 3;
    std::string name;
    std::cout << word << std::endl;
    std::cout << count << std::endl;
    std::cout << ratio << std::endl;
    std::cout << ready << std::endl;
    std::cout << word.size() << std::endl;
    std::cout << joined << std::endl;
    std::cout << word[0] << std::endl;
    std::cout << joined.find("cone") << std::endl;
    std::cout << joined.substr(5, 4) << std::endl;
    std::cout << count * 4 << std::endl;
    std::cout << 7 / 2 << std::endl;
    std::cout << 7.0 / 2 << std::endl;
    std::cout << (count > 1) << std::endl;
    std::cout << (count == 3) << std::endl;
    std::cout << !ready << std::endl;
    std::cout << static_cast<int>(price) << std::endl;
    std::cout << static_cast<double>(count) / 4 << std::endl;
    std::cout << static_cast<int>(ratio * 3) << std::endl;
    std::cout << limit << std::endl;
    std::cout << limit * count << std::endl;
    std::cout << scores[0] << std::endl;
    std::cout << scores[2] << std::endl;
    std::cout << total % 5 << std::endl;
    std::cout << step << std::endl;
    std::cout << (score >= goal) << std::endl;
    std::cout << (score < goal) << std::endl;
    std::cout << ((score >= goal) && (count == 2)) << std::endl;
    std::cout << ((score < goal) || wet) << std::endl;
    if (score >= goal) {
        result = "pass";
    } else {
        result = "retry";
    }
    std::cout << result << std::endl;
    if (wet) {
        std::cout << "wet" << std::endl;
    }
    switch (day) {
        case 1:
            name = "mon";
            break;
        case 2:
            name = "tue";
            break;
        case 3:
            name = "wed";
            break;
        default:
            name = "other";
            break;
    }
    std::cout << name << std::endl;
    for (int i = 0; i < 3; i++) {
        std::cout << i << std::endl;
    }
    int n = 3;
    while (n > 0) {
        std::cout << n << std::endl;
        n--;
    }
    for (int k = 0; k < 5; k++) {
        if (k == 2) {
            continue;
        }
        if (k == 4) {
            break;
        }
        std::cout << k << std::endl;
    }
    for (int value : scores) {
        std::cout << value << std::endl;
    }
    announce();
    show_label("tag");
    int scaled = scale(count);
    std::cout << scaled << std::endl;
    std::cout << scale(count, 3) << std::endl;
    mark_local();
    std::cout << count << std::endl;
    down(3);
    return 0;
}

Rebuild with g++ -std=c++17 types.cpp -o types, then run ./types. If g++ is missing and clang++ is the compiler you installed, swap only the tool name: clang++ -std=c++17 types.cpp -o types. The screen shows fifty-one lines. The lines through 2 match the scope page. The last three lines are 3, then 2, then 1.
Check the last three lines first. down(3) printed 3, then 2, then 1. The table gives each row its piece, so compare your run with it line by line. If the last line is 2, the down(3); call is missing. If the program never finishes, the stop is missing or the self-call does not shrink n. If down is missing above main, the new countdown never appears.

📊 The recursive countdown and what it shows

Piece What the screen shows
First call, because announce still runs first among the function calls
Last 1, because down(3) prints 3, then 2, then 1
Rule a function may call itself when each call moves toward a stop
Screen pine, 2, 0.5, 1, 4, pine cone, p, 5, cone, 8, 3, 3.5, 1, 0, 0, 7, 0.5, 1, 10, 20, 4, 6, 2, 7, 1, 0, 1, 0, pass, wed, 0, 1, 2, 3, 2, 1, 0, 1, 3, 4, 5, 6, call, tag, 4, 6, 9, 2, 3, 2, 1

Try one change at a time. Change down(3); to down(2);, leave the function body as it is, and rebuild. The last lines become 2, then 1, and the screen is shorter by one line, because the chain started one step closer to the stop. Put 3 back. Next, change the stop from n <= 0 to n <= 1, leave the call as down(3);, and rebuild. The chain prints 3, then 2, and stops before printing 1, because down(1) returns immediately. Put n <= 0 back. Each experiment changes one thing, so the screen shows exactly how the stop and the starting argument shape the countdown. Undo each change before the next one starts, so the file always returns to the checked version.
This page ends the recursion tool and stops before the next module. The next page is classes, which begins building a type with fields beyond these free functions. The down you have just written only shows a self-call with a stop. You leave with fifty-one lines on the screen, and the last one is 1. Count the lines before you leave. There are fifty-one, and the last one is 1.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
4
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top