foreach
loopIn 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.
The syntax for a foreach
loop is as follows:
for (data_type variable_name : container_type)
{
// code to be executed for each element
}
data_type
is a variable that will hold the current element during each iteration of the loop.variable_name
is the name of that variable.container_type
is the name of an array.foreach
loop in the arrayThe 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 << " ";}}
int
.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.foreach
loop in the stringThe 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 << " ";}}
#include <string>
library to use string
.string
of name str
.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.foreach
loop allows for a more concise and readable syntax than traditional for
loops.foreach
loop is limited to sequential iteration and does not support more advanced features such as reverse iteration or index-based iteration.Free Resources