Sum of Digits in C

Level 3107 keystrokes

Calculates the sum of digits in a number using modulo and division.

C code

// The number to process and a total starting at 0
1int num = 12345, sum = 0;
// One pass per digit
2while (num > 0) {
// num % 10 is the last digit (5, then 4, 3, 2, 1); add it to sum
3 sum += num % 10;
// Integer division drops that digit
4 num /= 10;
5}
// 1+2+3+4+5 gives Sum of digits: 15
6printf("Sum of digits: %d", sum);

Output

Sum of digits: 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.

  • ;× 4
  • =× 4
  • ,× 2
  • "× 2
  • (× 2
  • )× 2
  • %× 2
  • :× 1
  • {× 1
  • }× 1

More C examples at level 3

← C typing practice