Learning pathOriginal reference
Lesson 10 of 12

Nested loops: rows and columns

Translate a shape into two loop roles and count the total work.

One full inner loop per outer iteration

For a rectangle, the outer loop selects the row and the inner loop prints its columns. The inner counter starts over for each new row. A 2 by 3 rectangle needs six stars and two newlines.

The newline belongs inside the outer loop but after the inner loop. Inside the inner loop, it would put each star on a separate line; after both loops, it would join all rows together.

C++23
#include <iostream>

int main() {
    int rows = 0, columns = 0;
    std::cin >> rows >> columns; // Both between 1 and 20.
    for (int row = 1; row <= rows; ++row) {
        for (int column = 1; column <= columns; ++column) {
            std::cout << '*';
        }
        std::cout << '\n';
    }
    return 0;
}

Let the row determine the width

A growing triangle has row stars on each row. Keep the outer loop from 1 to n, but let the inner column counter stop at row rather than n. The row widths become 1, 2, 3, …, n.

Count inner-body executions to understand the work. A rectangle does rows × columns prints. A triangle does 1 + 2 + … + n prints. Formal complexity comes in Session 3, but already notice why a few lines of nested code can perform a huge amount of work.

Pause & predict

A growing triangle has n = 4. How many stars and newline characters are printed?

Choose an answer
Try it yourself

Turn the idea into code

Print a growing triangle for 1 ≤ n ≤ 20. For n = 3, output rows containing *, **, and ***.

Give me a hint

The inner loop’s bound is the current row number.

Show the explained solution

Row r prints exactly r stars. The outer loop visits every required row once, and the newline ends each row.

C++23
#include <iostream>

int main() {
    int n = 0;
    std::cin >> n;
    for (int row = 1; row <= n; ++row) {
        for (int column = 1; column <= row; ++column) {
            std::cout << '*';
        }
        std::cout << '\n';
    }
    return 0;
}

Your notes

Ready for the next idea?

Mark complete when you can explain it yourself.

From a problem to a programIdentify the input, output, and constraints, then translate a small plan into C++.Variables, types, and remembered valuesChoose a representation, initialize it, and understand what assignment really changes.Arithmetic without surprisesPredict division and remainder, widen before multiplication, and format decimal answers.Conditions and logical decisionsBuild exclusive categories, combine comparisons, and protect operations with short-circuit logic.Optional: other ways to chooseRecognize switch for exact choices and the conditional operator for choosing a value.For loops: make repetition preciseTrace initialization, condition, body, and update—and avoid an extra iteration.While, do-while, and stopping rulesChoose a loop from its stopping condition and read the exact input format.Break, continue, and early answersDistinguish leaving a loop from skipping one iteration, without losing required input.Five patterns worth understandingUse sums, counts, best-so-far candidates, products, and flags to process a stream.Nested loops: rows and columnsTranslate a shape into two loop roles and count the total work.Take a number apart, one digit at a timeUse remainder and division to process decimal digits, including zero.Multiple cases and a debugging mindsetCombine the patterns, isolate each case, and test the boundaries that can break your idea.Arrays: give every value a placeUnderstand indices, initialization, capacity, active length, and the first safe array loop.Scan, count, search, and compareDistinguish values from positions and preserve the exact tie rule a problem asks for.Change a sequence without losing itUpdate, copy, compare, reverse, and inspect neighbours using the correct bounds.Matrices: think in two coordinatesTraverse tables, total rows and columns, inspect diagonals, and protect grid neighbours.Characters become stringsSeparate characters from numbers, then safely inspect and edit managed text.Read the text the problem actually givesChoose words or full lines, preserve empty cases, and reset only the state that needs it.Scan text: count, filter, transformBuild a result from matching characters without losing leading zeros or skipping shifted text.Join, compare, and find textLearn content comparison, lexicographical order, substring counts, and the not-found sentinel.