C bootcamp · Lab 24

Sum of digits

easyWhile Loop10 minLesson: While Loop

Read the question, write C on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read a non-negative integer and print the sum of its digits.

n % 10 is the last digit; n /= 10 drops it. Loop until n is 0. Zero itself sums to 0.

Input. One integer n ≥ 0.

Output. One integer: the digit sum.

Constraints

  • 0 ≤ n ≤ 1 000 000 000

Examples

Example 1 — 1+2+3.
Input
123
Output
6
Example 2
Input
0
Output
0
Hint
  1. int total = 0; while (n > 0) { total += n % 10; n /= 10; }
  2. Handle n == 0 by printing 0 (the loop never runs).
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <stdio.h>

int main(void) {
  int n;
  if (scanf("%d", &n) != 1) return 1;
  if (n == 0) {
    printf("0\n");
    return 0;
  }
  int total = 0;
  while (n > 0) {
    total += n % 10;
    n /= 10;
  }
  printf("%d\n", total);
  return 0;
}
main.cC17 · gcc · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.