Sum of the digits of a number
Description: Write digit_sum(int n). For 9475 the answer is 25.
Hint:
n % 10is the last digit,n / 10removes it.
Solution
#include <iostream>
int digit_sum(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
int main() {
std::cout << digit_sum(9475) << ' ' << digit_sum(100) << ' ' << digit_sum(0) << '\n';
}
Output
25 1 0
How it works
- The loop adds the last digit and cuts it off, until the number is 0.
Read C++ while Loop.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |