Digit Sum with while
Completed
Read a non-negative integer and print the sum of its digits.
Input
One integer.
Output
The digit sum.
Example
Input
12345
Output
15
Editor
C++
Hints
n % 10 is the last digit; n /= 10 drops it.
Solution explanation
A while loop fits when you don't know the number of iterations in advance.
Show solution
#include <iostream>
using namespace std;
int main() {
long long n;
cin >> n;
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
cout << sum << "\n";
return 0;
}