Thursday, 22 June 2017 12:49

Written by
Rate this item

# Sum of digits program in C++

We can write the sum of digits program in C++ language by the help of loop and mathematical operation only.

## Sum of digits algorithm

To get sum of each digit by C++ program, use the following algorithm:

• Step 1: Get number by user
• Step 2: Get the modulus/remainder of the number
• Step 3: sum the remainder of the number
• Step 4: Divide the number by 10
• Step 5: Repeat the step 2 while number is greater than 0.

Let's see the sum of digits program in C++.

1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int n,sum=0,m;
6. cout<<"Enter a number: ";
7. cin>>n;
8. while(n>0)
9. {
10. m=n%10;
11. sum=sum+m;
12. n=n/10;
13. }
14. cout<<"Sum is= "<<sum<<endl;
15. return 0;
16. }

Output:

```Enter a number: 23
Sum is= 5
```
```Enter a number: 624
Sum is= 12``` ### Anish Sir

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

Call +91 74 88 34 7779  | Email : anishsingh@live.com