Course outline · 0% complete

0/27 lessons0%

Course overview →

Loops: while and for

lesson 3-3 · ~13 min · 8/27

Loops are where programs spend nearly all of their running time, so they are where speed is won or lost — and every DSA problem you will ever solve reads its input in one. C++ has Python's while, plus a counted for you will type thousands of times in your career.

while

int n = 3;
while (n > 0) {
    std::cout << n << "\n";
    n--;              // subtract 1, from lesson 2-2
}

Exactly Python's while, with parentheses and braces.

The classic counted for loop

Python's for i in range(5) becomes:

for (int i = 0; i < 5; i++) {
    std::cout << i << " ";
}
// 0 1 2 3 4

The three parts inside the parentheses, separated by semicolons:

  1. int i = 0 runs once, before the loop starts.
  2. i < 5 is checked before every iteration. False means stop.
  3. i++ runs after every iteration.

break and continue work exactly as in Python. The loop variable i only exists inside the loop, which is the scoping you want.

Code exercise · cpp

Run this. It sums the numbers 1 through 10 with a for loop.

Quiz

How many times does the body of `for (int i = 0; i < n; i++)` run when n is 4?

Nested loops

A loop inside a loop runs the inner body once for every combination: the outer loop picks a row, the inner loop runs fully for that row. This is the shape of grid traversal, comparing all pairs, and most "print a pattern" warm-ups:

for (int row = 1; row <= 4; row++) {
    for (int col = 1; col <= row; col++) {
        std::cout << "*";
    }
    std::cout << "\n";   // end the row
}

The inner bound is col <= row, so row 1 prints one star, row 2 prints two, and so on. Count the total work: 1 + 2 + 3 + 4 stars. Nested loops multiply work quickly — with both bounds at n, the body runs n × n times, a fact that becomes central when we measure algorithm cost in unit 8.

Code exercise · cpp

Your turn: run the triangle as written and confirm the 1-2-3-4 pattern. Then flip it so row 1 prints 4 stars and row 4 prints 1 star (change the inner loop's condition). The checker grades the starter as written.

Reading a known count of inputs

A pattern you will use in nearly every DSA problem: the first input says how many values follow, then you loop and read them.

int n;
std::cin >> n;          // how many numbers?
for (int i = 0; i < n; i++) {
    int x;
    std::cin >> x;      // read the next one
    // ... process x ...
}

Because >> skips all whitespace (lesson 1-2), it does not matter whether the numbers arrive on one line or many.

Code exercise · cpp

Your turn. The first input is a count n, followed by n integers. Print the largest one. Input is `5` then `3 9 2 9 4`, so the output must be `max = 9`. Start max at the first value, then compare the rest against it.