While Loop in C++

Level 252 keystrokes

Counts down with a while loop: n starts at 3, the loop prints 3, 2 and 1, and it stops when n reaches 0.

C++ code

// Initializes the counter n with 3
1int n = 3;
// Repeats the body as long as n is greater than 0
2while (n > 0) {
// Prints the current value of n (3, then 2, then 1)
3 cout << n << endl;
// Decreases n by 1; without this line the loop would never end
4 n--;
5}

Output

3
2
1
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
  • ;× 3
  • -× 2
  • (× 1
  • )× 1
  • {× 1
  • }× 1
  • =× 1
  • >× 1

More C++ examples at level 2

← C++ typing practice