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.
💡 Key insight
The range-based for loop, introduced in C++11, is now the preferred way to iterate over arrays and containers like vectors.
Syntax
syntax
for (init; condition; update) { }
for (type item : container) { } // range-basedExample
The range-based loop reads each element of nums in turn, without needing an index variable.
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;
}output1 2 3 4 5
Try it yourself
Copy this example into the C++ compiler and run it — try changing a value and see what happens.
