Home »
C++ STL
Range-based loop in C++ (similar to for-each loop)
C++ Range-based loop: Here, we are going to learn about the range-based loop in C++, which is similar to the for-each loop.
Submitted by Sanjeev, on April 20, 2019
Range-based loop in C++ (enhanced for loop)
for loop is used to execute a block of statements multiple times if the user knows exactly how many iterations are needed or required.
After the release of C++ 11, it supports an enhanced version of for loop, which is also called for-each loop or enhanced for loop. This loop works on iterable like string, array, sets, etc.
Syntax of range-based (for-each/enhanced for loop):
for (data_type variable : iterable){
//body of the loop;
}
It stores each item of the collection in variable and then executes it.
Note: auto keyword can be used instead of data_type which automatically deduce the type of the element. So type error can be reduced.
C++ code to demonstrate example of range-based loop
// C++ program to demonstrate example of
// range-based loop (for-each/ enhanced for loop)
#include <iostream>
using namespace std;
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
cout << "\n Demonstration of for-each in C++" << endl;
// Notice that instead of int, auto is used
// it automatically checks for the type of
// the variable so type error can be reduced
// using auto keyword
for (auto x : arr){
cout << " " << x << endl;
}
return 0;
}
Output
Demonstration of for-each in C++
1
2
3
4
5
6
7
8
9