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

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

I am using very simple logic. If we find 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 previous sum.

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

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

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#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

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.