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.
0 of 10 checks passed
Your progress is saved on this device.