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
using namespace std;
unsigned long i,p,n,sum=0;
cout<<"Enter any number:";
cout<<endl<<"Sum of digits is:"<<sum;
Enter any number:361
Sum of digits is:10