← C++ from Scratch
Lesson 19 of 62 · 10 XP
The for loop
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
for (int i = 0; i < 5; i++) {
std::cout << i << ' '; // 0 1 2 3 4
}
Three parts in the parentheses: the start (int i = 0), the condition for continuing (i < 5), the step (i++).
i exists only inside the loop.
Nested loops are for tables and grids:
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 4; col++)
std::cout << '#';
std::cout << '\n';
}
To go through a container there's range-for: for (int x : v) — "for each x in v".
Task. Read n and draw a "staircase" of * that is n lines high: line k has k stars.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.