Site Guide

Find your way around the Engineering Club.

Know what you need? Search for a component, concept or project.

Around the site

Start

Labs

TestingExperimental

Build

Club

LearnExperimental

Go a little deeper

Entry points to larger collections. Use Search for individual records.

Learning paths & reference

Inside PiCrawlerExperimental

Inside Inventory

← C++ Worked Programs

Learn / Worked program

Nested Loop Pattern Generator

Turn row geometry into precise loop bounds

BeginnerDesktop C++17 · runnable source

What you will learn

The complete source

main.cpp

main.cpp
#include <iostream>
#include <sstream>
#include <string>

bool readInteger(const std::string& prompt, int& value, int low, int high) {
    std::string line;
    while (std::cout << prompt && std::getline(std::cin, line)) {
        std::istringstream input(line);
        char extra = '\0';
        if (input >> value && !(input >> extra) && value >= low && value <= high) return true;
        std::cout << "Enter a whole number in [" << low << ", " << high << "].\n";
    }
    std::cerr << "Input ended before a valid integer was supplied.\n";
    return false;
}

void printTree(int height) {
    for (int row = 0; row < height; ++row) {
        for (int space = 0; space < height - row - 1; ++space) std::cout << ' ';
        for (int mark = 0; mark < 2 * row + 1; ++mark) std::cout << 'X';
        std::cout << '\n';
    }
    for (int space = 0; space < height - 1; ++space) std::cout << ' ';
    std::cout << "|\n";
}

int main() {
    int height = 0;
    if (!readInteger("Tree height (1 to 30): ", height, 1, 30)) return 1;
    printTree(height);
}
Source integrity

SHA-256 c33d2437eea0fbc1d09fb55edf281fa9ce6570c80bf105e58345ec264d3beb04. Display, copy and approved download use the same source.

What it does and why it was selected

The original experiment contains triple-index output, a small star table and a tree. The tree is the clearest visible result: each row explains why one loop controls vertical progress while other loops control horizontal layout. The canonical version keeps that coherent behavior rather than printing unrelated demonstrations together.

Actual execution

main reads an integer height from 1 through 30 and passes it by value to printTree. The outer loop selects row indices 0..height-1. Its first inner loop prints height-row-1 spaces, and the next prints 2*row+1 X marks. A newline finishes that row before the outer loop advances. After the canopy, a separate loop prints height-1 spaces followed by one trunk character. Height 4 therefore produces canopy widths 1,3,5,7; the trunk aligns with the center of the final seven-character row.

Mathematical or state model

The pattern is a small discrete geometry problem. Every canopy row has odd width, so its center mark can occupy the same horizontal position. Increasing width by two adds one mark to either side while reducing leading spaces by one. The total canopy marks are the sum of the first height odd numbers, height squared. The source does not add trailing spaces, because they contribute nothing visible in a normal terminal.

Design and C++ mechanics

Each loop variable has one job and lives inside its own for statement. The space variable from one row is not carried into the next row; the loop initializes it again. Omitting the newline would concatenate the rows into a single horizontal sequence. The height bound prevents a negative spacing model and excessively wide output. Changing the visible mark from X to a two-character token changes apparent alignment, which is why this version consistently uses single characters.

Historical differences and limits

The result is console text, not a geometric rendering engine. Variable-width fonts can distort it. No terminal clearing, hidden cursor or animation loop is necessary. The archived three-level index experiment independently used bounds 3,2,5, so it emitted 30 triples; that is a product of independent bounds, whereas this tree’s mark count depends on the current row. Treating these as the same kind of nested iteration misses the useful distinction.

Useful extensions

Add a right-aligned descending triangle and derive its bounds before writing loops. If introducing a rectangular grid, store rows in strings or a container only when the output needs later transformation. The current streaming output is simpler because each character is printed once and never revisited.

Source-linked explanations

Follow each line reference to its marked source region. The explanations below are bound to the reviewed source hash and preserve the supplied teaching layers.

Input contract and end-of-file

main.cpp, lines 5–15 →

Only validated whole integers are allowed to reach the Nested Loop Pattern Generator calculation.

Technical explanation
getline consumes a complete line, then a temporary istringstream attempts the numeric conversion. After conversion, trying to extract extra detects a trailing non-whitespace character. Failure of that second extraction means no unwanted data remains. The local stream can fail without putting cin into the historical repeated-failbit state. A fresh local stream is created for every attempt. Low/high comparisons establish the caller’s domain, and exhausting cin ends the while condition and returns false.
Syntax
The && operators evaluate left to right and short-circuit: range tests run only after numeric extraction succeeds. !(input >> extra) intentionally treats no remaining non-whitespace character as success. A double& or int& parameter writes the accepted value into the caller’s variable.
Effect on the program
The caller checks the returned bool and returns exit status 1 on EOF before calculation. Rejected lines are followed by another prompt; valid lines reach the model exactly once.
Common mistake
Clearing a permanently exhausted input stream and retrying cannot create new input. Accepting a numeric prefix such as 550x would silently change the input contract.
Deeper connection
Reliable input separates parsing from physical or algorithmic validity: a valid number still must lie in this program’s supported domain.

input validationconsole ioreferences

Dependent loop bounds make the shape

main.cpp, lines 17–25 →

row determines both horizontal loops.

Technical explanation
row determines both horizontal loops. At row zero, height-1 leading spaces center one mark. At row height-1, no leading spaces precede 2*height-1 marks. Each inner variable resets when its loop starts; the output newline returns rendering to the next row.
Syntax
Each inner variable resets when its loop starts; the output newline returns rendering to the next row.
Effect on the program
Each inner variable resets when its loop starts; the output newline returns rendering to the next row.
Common mistake
Using a fixed width for every row makes a rectangle. Failing to reset horizontal counters can collapse later rows.

nested loopsfunctions

The trunk has a separate alignment rule

main.cpp, lines 23–24 →

After the canopy outer loop finishes, its row variable is out of scope.

Technical explanation
After the canopy outer loop finishes, its row variable is out of scope. The trunk uses height-1 spaces, matching the center column shared by all odd-width canopy rows. It is a separate loop, not another canopy row with a narrower formula.
Syntax
It is a separate loop, not another canopy row with a narrower formula.
Effect on the program
It is a separate loop, not another canopy row with a narrower formula.
Common mistake
Using height-row-1 here would require a row value that no longer exists and would confuse two different stages.

loopsconsole io

Recorded input and output

Captured from the compiled canonical program in the supplied verification package. These are recorded terminal sessions, not an interactive browser runner.

Sample run

Arguments
None
Recorded exit status
0

Program input

4

Program output

Tree height (1 to 30):    X
  XXX
 XXXXX
XXXXXXX
   |
3 more recorded behavior and error cases
one
Arguments
None
Recorded exit status
0

Program input

1

Program output

Tree height (1 to 30): X
|
zero recover
Arguments
None
Recorded exit status
0

Program input

0
4

Program output

Tree height (1 to 30): Enter a whole number in [1, 30].
Tree height (1 to 30):    X
  XXX
 XXXXX
XXXXXXX
   |
eof
Arguments
None
Recorded exit status
1

Program input

No standard input.

Program output

Tree height (1 to 30): 

Error output

Input ended before a valid integer was supplied.

Build and run

From this folder, with a configured C++17 compiler:

sh
g++ -std=c++17 -Wall -Wextra -Wpedantic main.cpp -o program
./program

On Windows GCC, build with -o program.exe and use .\program.exe. These are desktop examples; VS Code is an editor, the compiler builds an executable, and the terminal runs it.

Windows run command from the supplied metadata: .\program.exe.

Desktop compiler setup and platform limits. How headers and translation units fit together.

Verification and provenance

  • Source inspected
  • Compile verified
  • Warning reviewed
  • Behavior verified
  • Sanitizer checked

Supplied evidence: 4 recorded behavior/error cases and 4 address/undefined-behavior sanitizer cases for this exact source. These are tested cases, not an exhaustive correctness claim.

Recorded compiler: g++ (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0.

LeakSanitizer: disabled because unavailable under runtime tracing. Windows/MSVC and macOS execution are not certified by this evidence.

Source origin and publication treatment

Modernized user supplied source

User-supplied origin; no independent authorship or license determination. Instructor code is not included.

New or rewritten source, limited sanitized historical excerpts when useful

No new license is asserted by this publication.