Flash cards
Review the key moves
What is the main idea behind C++ The foreach Loop?
Lesson checks
Practice each idea before moving on
Short Mimo-style checks built from this lesson's code, terms, and sequence.
Which statement best captures the main point of this lesson?
Complete the missing token from the example code.
___ ( type variableNamePut the learning moves in the order that makes the concept easiest to apply.
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).