## Description of sum of digits problem

In this sum of digits problem we have to find the sum of all the digits of an integer given by the user. We already have discussed about determining sum of digits in our C++ programming section. You can take the idea to solve this problem from there.

However, in this guide we will see the solution of this sum of digits problem. We have taken this problem from CodeChef for practice and learning purpose only. After taking the number form the user we will calculate the the sum of digits of that number here.

## Solution to sum of digits problem

For determining the sum we will take the input first which will be the test case of this program. Ten each test case will take a number and calculate the sum of digits like bellow;

Assume, the user gives 5634 to find the sum of digits. The program will calculate,

**(5 + 6 + 3 + 4) = 18**

We can implement the logic to find the sum in different way which we have discussed in our sum of digits in C and sum of digits in C++ articles. If you have successfully completed those two guide then this program will be very simple to solve for you.

Now, let’s see the source code to find the sum of digits in C++ bellow.

```
// sum of digits problem solving in C++
#include <iostream>
using namespace std;
int main(){
int t, sum = 0;
cin >> t;
for(int i = 1; i <= t; i++){
int num;
cin >> num;
while(num > 0){
sum += num % 10;
num /= 10;
}
cout << sum << endl;
sum = 0;
}
}
```

Compile and run the above program in your editor to get the output like this.

```
3
12345
15
31203
9
2123
8
```

- Here, the first line contains the test case.
- Second line contains the number for first test case of which we have to calculate the sum of digits.
- Third line is the output for the first test case which have printed
**15.** - Because (1 + 2 + 3 + 4 + 5 = 15).
- Similar process for other test case also.

**Previous page**: **Find reminder**

**Next page**: **Enormous input test**

**Recommended for you**: