In C++, the for-each loop—also known as the range-based for loop—is used to iterate through arrays and other data structures.
How the For-Each Loop Works
Instead of handling index values manually like in traditional loops, the for-each loop directly accesses each element.
Syntax
C++
x
for (type variableName : arrayName) {
// Code block to execute for each element
}
Example: Listing Motorcycle Models
C++
using namespace std;
int main() {
string bikeModels[] = {"R1", "CBR600RR", "ZX-10R", "MT-09"};
for (string model : bikeModels) {
cout << "Model: " << model << "\n";
}
return 0;
}
Output:
C++
Model: R1
Model: CBR600RR
Model: ZX-10R
Model: MT-09
Example: Processing Engine Displacement Values
C++
using namespace std;
int main() {
int engineSizes[] = {600, 1000, 1100, 1300};
for (int cc : engineSizes) {
cout << "Engine displacement: " << cc << "cc\n";
}
return 0;
}
Output:
C++
Engine displacement: 600cc
Engine displacement: 1000cc
Engine displacement: 1100cc
Engine displacement: 1300cc