C++The foreach Loop
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 anarray (or otherdata structures):
Syntax
for (type variableName:arrayName) {
// code block to be executed
}
// 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";
}
Try it Yourself »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:
Note: Don't worry if you don't understand the examples above. You will learn more about arrays in theC++ Arrays chapter.
Good to know: Thefor-each loop was introduced in C++ version 11 (2011).

