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.
#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.
A growing triangle has n = 4. How many stars and newline characters are printed?
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.
#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
Mark complete when you can explain it yourself.