What is the foreach loop in C++?

The foreach loop

In C++, the foreach loop (also known as the range-based for loop) is a feature that allows us to iterate over the elements of an array, container, or other sequences of elements.

Syntax

The syntax for a foreach loop is as follows:

for (data_type  variable_name : container_type) 
{
    // code to be executed for each element
}
  • The data_type is a variable that will hold the current element during each iteration of the loop.
  • The variable_name is the name of that variable.
  • The container_type is the name of an array.

The foreach loop in the array

The following code demonstrates the use of the foreach loop for an array:

#include <iostream>
using namespace std;
int main()
{
int array[] = {1, 2, 3, 4, 5};
for (int x : array)
{
cout << x << " ";
}
}

Explanation

  • Line 6: Initialize an array of type int.
  • Line 7–10: The for keyword begins the loop. This loop iterates over all the elements in the array container. For each element, it assigns the element to the variable x and prints it to the console.

The foreach loop in the string

The following code demonstrates the use of the foreach loop for a string:

#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "Educative";
for (char c : str)
{
cout << c << " ";
}
}

Explanation

  • Line 2: Add #include <string> library to use string.
  • Line 7: Initialize a string of name str.
  • Line 7–10: The for keyword begins the loop. This loop iterates over all the elements in the str. For each element, it assigns the element to the variable c of type char and prints it to the console.

Advantages

  • Simplicity and readability: The foreach loop allows for a more concise and readable syntax than traditional for loops.

Disadvantages

  • Limited functionality: The foreach loop is limited to sequential iteration and does not support more advanced features such as reverse iteration or index-based iteration.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved