range-based for loop c++ for integer code example
Example 1: iterate over a range in c++
for (int i=0; i<5; ++i) {
cout << i << " ";
}
// output is 0 1 2 3 4; note 5 is excluded since < is used and not <=
Example 2: range based for loop c++ with reference
1
2
3
4
5 using namespace std;
6
7 int main(){
8 array<int, 5> d = {1, 2, -1, 3, 5};
9 cout << "Items before modification: " << endl;
10 for (int item : d){
11 cout << item << " ";
12 }
13 //multiple elements of d by 3
14 for (int &itemRef : d){
15 itemRef *= 3;
16 }
17 cout << endl << "Items after modification: " << endl;
18 for (int item : d){
19 cout << item << " ";
20 }
21 cout << endl;
22 return 0;
23 }