bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/C++/C++ Tutorial
C++•C++ Tutorial

C++ The foreach Loop

Flash cards

Review the key moves

1/4
Core idea

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.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___ ( type variableName
3Order

Put the learning moves in the order that makes the concept easiest to apply.

The following example outputs all elements in an array, using a " for-each 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 ):
Loop Through a String

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).

Previous

C++ Nested Loops

Next

C++ Break and Continue