Range-Based For Loop in C++

Level 265 keystrokes

Uses a range-based for loop to visit each element of the array {1, 2, 3} in order and prints 1, 2 and 3.

C++ code

// Declares an int array with three elements
1int nums[] = {1, 2, 3};
// for (int n : nums) gives n each element in turn, with no index needed
// n is a copy of the element, so changing n would not change nums
2for (int n : nums) {
// Prints the current element on its own line
3 cout << n << endl;
4}

Output

1
2
3
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 4
  • ,× 2
  • ;× 2
  • {× 2
  • }× 2
  • :× 1
  • (× 1
  • )× 1
  • [× 1
  • ]× 1

More C++ examples at level 2

← C++ typing practice