C++ Arrays and Loops

In C++, arrays are often used with loops to efficiently process multiple elements without manually handling individual values.

Tutorials dojo strip



Looping Through an Array

Using a for loop, you can iterate through each element in an array.

Example: Displaying Motorcycle Brands

#include <iostream>
using namespace std;

int main() {
    // Create an array of motorcycle brands
    string bikeBrands[5] = {"Yamaha", "Ducati", "Kawasaki", "Honda", "Harley-Davidson"};

    // Loop through the array
    for (int i = 0; i < 5; i++) {
        cout << bikeBrands[i] << "\n";
    }

    return 0;
}

Output:

Yamaha  
Ducati  
Kawasaki  
Honda  
Harley-Davidson  




Displaying Index Alongside Values

To show the index along with each value, use i within the loop.

Example

#include <iostream>
using namespace std;

int main() {
    string bikeBrands[5] = {"Yamaha", "Ducati", "Kawasaki", "Honda", "Harley-Davidson"};

    for (int i = 0; i < 5; i++) {
        cout << i << " = " << bikeBrands[i] << "\n";
    }

    return 0;
}

Output:

0 = Yamaha  
1 = Ducati  
2 = Kawasaki  
3 = Honda  
4 = Harley-Davidson  




Looping Through an Array of Numbers

Arrays can also store numerical values, such as engine capacities.

Example: Displaying Engine Sizes

#include <iostream>
using namespace std;

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

    for (int i = 0; i < 5; i++) {
        cout << engineSizes[i] << "\n";
    }

    return 0;
}

Output:

600  
1000  
1100  
1300  
1500  




The For-Each Loop (Range-Based Loop)

Introduced in C++11, the for-each loop (or range-based for loop) simplifies iteration by automatically handling each array element.

Syntax

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



Example: Iterating Over Engine Sizes

#include <iostream>
using namespace std;

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

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

    return 0;
}




Example: Iterating Over Motorcycle Brands

#include <iostream>
using namespace std;

int main() {
    string bikeBrands[5] = {"Yamaha", "Ducati", "Kawasaki", "Honda", "Harley-Davidson"};

    for (string brand : bikeBrands) {
        cout << "Brand: " << brand << "\n";
    }

    return 0;
}
Tutorials dojo strip
Scroll to Top