While Loop Sum in C++

Level 278 keystrokes

Adds the numbers 1 to 5 to sum with a while loop and prints the total, 15.

C++ code

// sum collects the running total and starts at 0
1int sum = 0;
// i is the number to add next, starting at 1
2int i = 1;
// Repeats while i is 5 or less
3while (i <= 5) {
// Adds i to sum: 1, 3, 6, 10, 15
4 sum += i;
// Moves on to the next number; the loop ends when i becomes 6
5 i++;
6}
// Prints the total, 15
7cout << sum << endl;

Output

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

  • ;× 5
  • <× 5
  • =× 4
  • +× 3
  • (× 1
  • )× 1
  • {× 1
  • }× 1

More C++ examples at level 2

← C++ typing practice