Sum of Digits in Number

To find the sum of digits in number n in C++, pop the last digit of number in a loop and accumulate it in a variable, until there are no digits left in the number.

In the following program, we read a number to n from user via console input, and find the sum of digits in this number.

C++ Program

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter a number : ";
    cin >> n;
    
    int sum = 0;
    while (n > 0) {
        sum = sum + (n % 10);
        n = n / 10;
    }
    
    cout << "Sum of digits : " << sum << endl;
}

Output

Enter a number : 12345
Sum of digits : 15
Program ended with exit code: 0
Enter a number : 224466
Sum of digits : 24
Program ended with exit code: 0

We have used C++ While Loop for iteration.

Conclusion

In this C++ Tutorial, we learned how to find the sum of digits in a number, with example.