# Print Sum of Digits in Given Number using C++

Confronting with numbers is the first thing each one of us has learned in school. However, as we step up high more and more difficult questions based on the same fundamentals seem to appear in our way. It’s the same with programming, using the same fundamentals to find solutions for multiple complex problems. Now the cool thing is, you can be creative in your way eventually coming up with a unique solution. And if you’re able to do this, then you’ve clearly understood how to use programming for others and your good. But keeping that aside, we’ve talked about numbers before. So what if we do simple addition, seems too easy right!. So let’s quickly find out how to Print Sum of Digits in Given Number using C++.

With the help of this program, you will be able to find the addition of digits in a number. Practicing these types of questions also helps to get an upper edge in

## What’s The Approach?

• To store the sum of digits in a number we’ll use a variable `sum` initialized to 0.

• Now we’ll perform a modulo operation with 10 on the number to get the rightmost digit as the remainder.

• The above two instructions will keep executing till the value of our input number becomes less than `0`.

## C++ Program To Print Sum of Digits in Given Number

Input:

`687`

Output:

`21`

```// C++ program to compute sum of digits in
// number.
#include <iostream>
using namespace std;

/* Function to get sum of digits */
class TechDecodeTutorials {
public:
int getSum(int n)
{
int sum = 0;
while (n != 0) {
sum = sum + n % 10;
n = n / 10;
}
return sum;
}
};

// Driver code
int main()
{
TechDecodeTutorials TDT;
int n = 687;
cout << TDT.getSum(n);
return 0;
}

``` #### Ethix

I'm a coding geek interested in cyberspace who loves to write and read