Loops

Programming Languages · C++ Loops & Vectors · 12 min

Repeat code with while and for, skip or stop with continue and break, and add things up.

Repeat with while

A loop repeats code. A while loop keeps going as long as its condition is true:

int count = 1;
while (count <= 3) {
    std::cout << count << "\n";
    count++;
}

That prints 1, 2, 3. Don't forget count++: without it the condition stays true forever.

  • Use a while loop to print the numbers 1 to 5, each on its own line.

The for loop

A for loop packs the three parts of a loop onto one line: where to start, when to keep going, and how to step:

for (int i = 0; i < 3; i++) {
    std::cout << "Hi\n";
}

i goes 0, 1, 2, so this prints Hi three times.

  • Use a for loop to print Hip hip hooray! 3 times.

Counting down

The step doesn't have to be i++. Count down with i--, or jump with i += 2:

for (int i = 10; i >= 0; i -= 5) {
    std::cout << i << "\n";   // 10, 5, 0
}
  • Use a for loop to count down from 5 to 1, one number per line.

  • After the loop, print Liftoff!.

Skip and stop: continue and break

Two handy words inside a loop:

  • continue skips the rest of this round and jumps to the next one
  • break stops the loop completely
for (int i = 1; i <= 5; i++) {
    if (i == 2) {
        continue;   // 2 is skipped
    }
    std::cout << i << "\n";
}

Put them before the print, so the print is skipped too.

  • Use continue so the loop skips 3.

  • Use break to stop the loop when i reaches 6 (don't print 6).

A running total

To add things up, start a variable at 0 before the loop, then add to it each time round. This is called a running total:

int total = 0;
for (int i = 1; i <= 3; i++) {
    total += i;      // 1, then 3, then 6
}
std::cout << total << "\n";   // 6
  • Use a for loop to add the numbers 1 to 10 into total.

  • After the loop, print Total: 55 using total.

Put it together: times table

Print the first five lines of the 7 times table, using a loop:

7 x 1 = 7
7 x 2 = 14
...
7 x 5 = 35

Let C++ do the multiplying with n * i.

  • Write a for loop where i goes from 1 to 5.

  • Inside it, print a line like 7 x 1 = 7 using n, i and n * i.

More in C++ Loops & Vectors

Previous: Conditionals · Next: Vectors