bhylu.com

Advertisements

C++ Recursion

Compute a bounded cumulative count and identify the base case before making another call.

How it works

A recursive function calls itself on a smaller problem. It requires a base case and a step that moves toward it. Every call consumes implementation resources; tail-call optimisation is not guaranteed by the language. This example sums one through n with an explicit small upper bound. It teaches the call structure, not a recommendation to use deep recursion for a large manifest. Iteration or a checked closed formula is more suitable when input size is unbounded.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror recursion.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · recursion.cpp

#include <iostream>

unsigned triangular(unsigned n) {
    if (n == 0) { return 0; }
    return n + triangular(n - 1);
}

int main() {
    unsigned n{5};
    if (n > 100) { return 1; }
    std::cout << "Cumulative: " << triangular(n) << '\n';
}

Expected result

Cumulative: 15

The zero case returns immediately. Each other call contributes its current value and requests the remaining total. The selected bound keeps the numeric result representable even on a small unsigned type; it does not promise a portable stack capacity. A recursive tree walk must also consider an adversarially tall tree rather than assuming every tree is balanced.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.