C++ bootcamp · Lab 23

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.

Input. One line: an integer n ≥ 0.

Output. One integer: the digit sum.

Constraints

  • 0 ≤ n ≤ 1000000000

Examples

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

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

#include <iostream>

int main() {
  int n;
  std::cin >> n;
  if (n == 0) {
    std::cout << "0\n";
    return 0;
  }
  int total = 0;
  while (n > 0) {
    total += n % 10;
    n /= 10;
  }
  std::cout << total << "\n";
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.