Definition
📌 Loops
C++ supports the same for, while, and do-while loops as C, plus a modern addition: the range-based for loop, which iterates directly over a container's elements without manual indexing..
Syntax
syntax
for (init; condition; update) { }
for (type item : container) { } // range-basedExample
cpp
#include <iostream>
using namespace std;
int main() {
int nums[] = {1, 2, 3, 4, 5};
for (int n : nums) {
cout << n << " ";
}
cout << endl;
return 0;
}Output
output1 2 3 4 5
Important Points
- Range-based for loops reduce off-by-one errors since there's no manual index.
- Use
for (auto& item : container)to modify elements in place without copying. break/continuework the same as in C.whileanddo-whilebehave identically to their C counterparts.
Common Mistakes
- Using a range-based for loop when you actually need the index too — use a classic for loop instead.
- Copying large elements unnecessarily by not using
&in a range-based loop. - Forgetting to update the loop variable in a classic
whileloop, causing an infinite loop.
Interview Tip
🎯 Before your interview
Know when a range-based for loop isn't enough — e.g. when you need the current index, a classic for loop is still the right tool.
