C++ The foreach Loop

Welcome to The Coding College! In this tutorial, we’ll explore the foreach loop in C++, also known as the range-based for loop, which simplifies iteration over collections like arrays, vectors, and other container types.

What is the foreach Loop in C++?

The foreach loop (introduced in C++11 as the range-based for loop) provides a convenient way to iterate through all elements of a collection without needing an explicit index.

Syntax

for (datatype variable : collection) {
    // Code to execute
}

Key Points:

  1. The loop iterates through every element in the collection.
  2. You can use the loop variable directly to access each element.
  3. Works with standard containers like arrays, vectors, and user-defined collections.

Example 1: Iterating Over an Array

#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40, 50};

    cout << "Array elements: ";
    for (int num : numbers) {
        cout << num << " ";
    }

    return 0;
}

Output:

Array elements: 10 20 30 40 50

Example 2: Modifying Elements (Pass by Reference)

To modify elements of a collection, use a reference (&) in the loop variable.

#include <iostream>
using namespace std;

int main() {
    int numbers[] = {1, 2, 3, 4, 5};

    for (int& num : numbers) {
        num *= 2;  // Multiply each element by 2
    }

    cout << "Modified array: ";
    for (int num : numbers) {
        cout << num << " ";
    }

    return 0;
}

Output:

Modified array: 2 4 6 8 10

Example 3: Using the foreach Loop with Vectors

The foreach loop works seamlessly with std::vector, a dynamic array in C++.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<string> fruits = {"Apple", "Banana", "Cherry"};

    cout << "Fruits: ";
    for (const string& fruit : fruits) {
        cout << fruit << " ";
    }

    return 0;
}

Output:

Fruits: Apple Banana Cherry

Example 4: Sum of Elements

Use a range-based for loop to calculate the sum of elements in an array.

#include <iostream>
using namespace std;

int main() {
    int numbers[] = {1, 2, 3, 4, 5};
    int sum = 0;

    for (int num : numbers) {
        sum += num;
    }

    cout << "Sum of array elements: " << sum << endl;

    return 0;
}

Output:

Sum of array elements: 15

Example 5: Iterating Over Multidimensional Arrays

The foreach loop can also iterate over multidimensional arrays.

#include <iostream>
using namespace std;

int main() {
    int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};

    cout << "Matrix elements: " << endl;
    for (const int(&row)[3] : matrix) {  // Iterate through rows
        for (int elem : row) {          // Iterate through elements in a row
            cout << elem << " ";
        }
        cout << endl;
    }

    return 0;
}

Output:

Matrix elements:  
1 2 3  
4 5 6

Example 6: Using foreach with Maps

You can iterate through a std::map using a foreach loop to access keys and values.

#include <iostream>
#include <map>
using namespace std;

int main() {
    map<string, int> scores = {{"Alice", 90}, {"Bob", 85}, {"Charlie", 88}};

    cout << "Student Scores: " << endl;
    for (const auto& pair : scores) {
        cout << pair.first << ": " << pair.second << endl;
    }

    return 0;
}

Output:

Student Scores:  
Alice: 90  
Bob: 85  
Charlie: 88  

Advantages of the foreach Loop

  1. Simpler Syntax: No need for index management or manually incrementing variables.
  2. Safety: Reduces the risk of off-by-one errors.
  3. Readability: Code is more concise and easier to understand.
  4. Automatic Compatibility: Works with STL containers and arrays out-of-the-box.

Best Practices for Using foreach Loops

  • Use const When Possible: Add const to prevent accidental modification of elements.
for (const auto& elem : collection) { /* Safe and non-modifying */ }
  • Pass by Reference for Efficiency: Use references (&) for large objects to avoid unnecessary copying.
for (const auto& largeObject : container) { /* Efficient iteration */ }
  • Modify Only When Needed: Use references (&) only when modifying elements.
  • Avoid Manual Indexing: The foreach loop automatically handles indices for you.

When to Use the foreach Loop

  • Iterating through arrays, vectors, maps, or other containers.
  • When you don’t need to modify elements or access their indices directly.
  • For clean and concise iteration over collections.

Explore More at The Coding College

Learn more about C++ loops, data structures, and algorithms at The Coding College. Explore hands-on tutorials and practical examples to master C++ programming.

What’s Next?

  • Learn about standard library algorithms like std::for_each.
  • Dive into advanced data structures like sets and maps.
  • Explore lambda functions to make loops even more powerful.

Leave a Comment