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
Input
123
Output
6
Input
0
Output
0
Hint
- If n is 0 the loop never runs — print 0.
- 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.