Loops

Loops allow us to automate repetition. In this section we’ll review while, do while, and for loops.

Table of Contents

  1. While and Do While Statements
  2. Data Validation
  3. For Statements
  4. Multi-Counter For Loops
  5. Auto With For
  6. Nested Loops
  7. Loops for Arrays and Objects
  8. Further Reading

While and Do While Statements

C++ contains standard while and do while loops. They work as you might expect:

while (booleanCondition) {
  // Loop body will execute over and over while booleanCondition remains true.
}

do {
  // Loop body executes at least once, and then repeatedly while booleanCondition remains true.
} while (booleanCondition);

Data Validation

An intentionally infinite do while loop can be helpful when validating user input:

For Statements

Standard C-style for loops are also available. These loops are best used for counting tasks:

for (int apples{10}; apples <= 20; apples++) {
  std::cout << apples << ": How do you like them apples?\n";
}

💡 Best Practice:

Always use braces, even though they are optional for single statement loops.

Multi-Counter For Loops

There’s nothing stopping you from using multiple counters in your for loops:

for (int x{0}, y{9}; x < 10; ++x, --y) {
    std::cout << x << ' ' << y << '\n';
}

🎵 Note:

The two update expressions are separated by a comma.

Auto With For

It’s common to see the auto keyword used with loop variable initialization:

for (auto apples{10}; apples <= 20; apples++) {
  std::cout << apples << ": How to you like them apples?\n";
}

Nested Loops

Loops can go inside of loops inside of other loops.

⚡ Warning:

“Expensive” operations inside of nested loops can lead to performance issues.

Loops for Arrays and Objects

⏳ Wait For It:

There are special loops for traversing collections. See the “ranged-base for” notes in the vector module.

Further Reading