Sum of the digits of a number

Description: Write digit_sum(int n). For 9475 the answer is 25.

Hint:

  • n % 10 is the last digit, n / 10 removes 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
C++ if, else if and else
C++ switch Statement
C++ for Loop and Range based for
C++ while and do while Loop
C++ break, continue and goto
Exercises & Assignments
Find the largest of three numbers
Check if a year is a leap year
FizzBuzz in C++
Sum of the digits of a number
Print a multiplication table
Check prime numbers and list the primes up to 30
Interview Questions & Answers
No Content Found.