Skip to content

Chapter 6 of 31

Loops

Repeat work with for, range-for, while, do-while, break, and continue.

28 minutes 10 quick checksBy Subha Prasad
Lesson 6 of 31Course navigation

Lesson content

Read, practise, then check your understanding

Use a classic for loop when initialization, condition, and update form one counting operation. Use while when repetition is controlled by an event or read, and do-while when the body must run at least once.

#include <iostream>
#include <vector>

std::vector<int> values{2, 4, 6};
int sum{};
for (const int value : values) {
    sum += value;
}

int input{};
while (std::cin >> input) {
    if (input < 0) break;
    if (input == 0) continue;
    std::cout << 100 / input << '\n';
}

A range-for avoids index errors. Use const auto& for read-only access to large elements and auto& when elements must change. break exits the nearest loop; continue advances to its next iteration.

Correctness and complexity

State the invariant: what remains true before and after each iteration. Ensure the loop makes progress and that its boundary handles empty and one-element ranges. Beware mixing signed counters with unsigned container sizes. Prefer std::size_t or avoid indexing.

Nested loops often multiply work: two full passes over n elements are usually O(n²). Standard algorithms such as std::find, std::transform, and std::accumulate express intent and reduce bookkeeping. When modifying a container during traversal, check its iterator invalidation rules; vector growth can invalidate every iterator and reference.

Knowledge check

Answer every question correctly to complete this chapter.

Which loop naturally traverses every element?
Which loop executes at least once?
What does continue do?
What does break do?
Why use const auto& in a range-for over large objects?
How many times does for (int i=0; i<3; ++i) run?
What does for (;;) create?
Why prefer algorithms when they clearly fit?
What can invalidate an iterator during a loop?
What complexity do two n-sized nested loops usually have?

0 of 10 checks passed

Your progress is saved on this device.

Loops | C++ Lesson | Subha Prasad