# Sum of Digits of a Number in C++

Below I have shared a C++ program to find the sum of the digits of a number.

For example, given number is 238 then the sum of digits will be 13.

I am using very simple logic. If we find the mod of any number by 10 then the result is the last digit of the number. For example, 123%10 is 3. In this way, I am extracting digits one by one and adding to the previous sum.

If a number is divided by 10 then the result is the number with the last digit removed. For example, 123/10 is 12. In this way, I am removing the digits one by one from the end.

I have performed these operations inside while loop until the number is not equal to 0.

## C++ Program to Find Sum of Digits of a Number

``````#include<iostream>

using namespace std;

int main()
{
unsigned long i,p,n,sum=0;
cout<<"Enter any number:";
cin>>n;

while(n!=0)
{
p=n%10;
sum+=p;
n=n/10;
}

cout<<endl<<"Sum of digits is:"<<sum;
return 0;
}``````

Output:

Enter any number:361
Sum of digits is:10

### 8 thoughts on “Sum of Digits of a Number in C++”

1. Thank you for this help but what is meaning of i and p. Need some more details on how to understand this layout and be able to explain it to somebody else.

2. Abhishek Singh Thakur

I have run this program and if I enter no. having more than 10 digits say 111111111111111 it is showing wrong result

3. Sum of all digit the result is in single digit for example 3453 the result is 6 3+4+5+3=15 next 1+5=6 please develop code and send mail id thank you

4. I don’t get it
If I enter a number 723
Sum is supposed to be 12
But according to the programme I’m getting 5 as my answer
Plz help..

1. I have checked, it is giving correct answer for 723, the answer is 12. Don’t know why it is giving wrong in your case.

5. // in c++
int n,sum=0;
cin>>n;
int arr[n];
for(int i=0;i<n:i++){
sum=sum+arr[i];
}
cout<<sum;
return 0;