The foreach Loop
There is also a " for-each loop" (also known as ranged-based for loop), which is used to loop through elements in an array (or other data structures ):
Syntax
for ( type variableName
: arrayName ) {
// code block to be executed
}The following example outputs all elements in an array, using a " for-each loop":
Example
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int num : myNumbers) {
cout << num << "\n";
}Loop Through a String
You can also use a for-each loop to loop through characters in a string:
Example
string word = "Hello";
for (char c : word) {
cout << c << "\n";
}Note
Don't worry if you don't understand the examples above. You will learn more about arrays in the C++ Arrays chapter . Good to know : The for-each loop was introduced in C++ version 11 (2011).
Good to know : The for-each loop was introduced in C++ version 11 (2011).