Do-While Loop in C

Level 397 keystrokes

Calculates factorial using a do-while loop that executes at least once.

C code

// Compute 5!
1int n = 5;
// The product starts at 1, the neutral value for multiplication
2int factorial = 1;
// do-while runs the body first and checks the condition afterwards, so it runs at least once
3do {
// Multiply by n: 5, then 4, 3, 2, 1
4 factorial *= n;
// Move to the next smaller factor
5 n--;
// Repeat while n > 0; the semicolon after while is required
6} while (n > 0);
// 5 * 4 * 3 * 2 * 1 = 120
7printf("%d", factorial);

Output

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

  • ;× 6
  • =× 3
  • -× 2
  • "× 2
  • (× 2
  • )× 2
  • ,× 1
  • {× 1
  • }× 1
  • *× 1

More C examples at level 3

← C typing practice