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_typeis a variable that will hold the current element during each iteration of the loop. - The
variable_nameis the name of that variable. - The
container_typeis 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
forkeyword begins the loop. This loop iterates over all the elements in thearraycontainer. For each element, it assigns the element to the variablexand 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 usestring. - Line 7: Initialize a
stringof namestr. - Line 7β10: The
forkeyword begins the loop. This loop iterates over all the elements in thestr. For each element, it assigns the element to the variablecof typecharand prints it to the console.
Advantages
- Simplicity and readability: The
foreachloop allows for a more concise and readable syntax than traditionalforloops.
Disadvantages
- Limited functionality: The
foreachloop 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