C++ Foreach Loop

In C++, the for-each loop—also known as the range-based for loop—is used to iterate through arrays and other data structures.

Tutorials dojo strip



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

for (type variableName : arrayName) {  
    // Code block to execute for each element  
}




Example: Listing Motorcycle Models

#include <iostream>
using namespace std;

int main() {
    string bikeModels[] = {"R1", "CBR600RR", "ZX-10R", "MT-09"};  

    for (string model : bikeModels) {  
        cout << "Model: " << model << "\n";
    }

    return 0;
}

Output:

Model: R1  
Model: CBR600RR  
Model: ZX-10R  
Model: MT-09  




Example: Processing Engine Displacement Values

#include <iostream>
using namespace std;

int main() {
    int engineSizes[] = {600, 1000, 1100, 1300};  

    for (int cc : engineSizes) {  
        cout << "Engine displacement: " << cc << "cc\n";
    }

    return 0;
}

Output:

Engine displacement: 600cc  
Engine displacement: 1000cc  
Engine displacement: 1100cc  
Engine displacement: 1300cc  
Tutorials dojo strip
Scroll to Top