C++ - Sum of Digits of a Number
Problem Statement
Brief Description
According to the problem statement we have to write a program in C++ that will take an integer value as input from the user through the keyboard and will count the total number of digits present in that number.
For example, if the user enters 132 as input, the program will generate 3 as output since the number 132 contains 3 digits.
Program
#include
#include
using namespace std;
int main()
{
int num,temp,rem,sum=0;
cout<<"Enter a number: ";
cin>>num;
temp=abs(num);
while(temp!=0)
{
rem=temp%10;
sum=sum+rem; //OR sum+=rem;
temp=temp/10; //OR temp/=10;
}
cout<<"Sum of the digits present in "<
Output
Enter a number: 132 Sum of the digits present in 132 is 6
Explanation
- 4 integer variable namely num, temp, rem and sum are declared.
- Initially 0 is stored in sum.
- The integer value entered by the user is stored in num.
- The absolute value corresponding to the entered value is stored in temp.
num | temp!=0 | rem=temp%10; | rem | sum=sum+rem; | sum | temp=temp/10; | temp | Comment |
---|---|---|---|---|---|---|---|---|
132 | - | - | - | - | 0 | - | 132 | Initial Values |
132 | 132!=0 ↓ 1(True) | rem=132%10; | 2 | sum=0+2; | 2 | temp=132/10; | 13 | Iteration 1 |
132 | 13!=0 ↓ 1(True) | rem=13%10; | 3 | sum=2+3; | 5 | temp=13/10; | 1 | Iteration 2 |
132 | 1!=0 ↓ 1(True) | rem=1%10; | 1 | sum=5+1; | 6 | temp=1/10; | 0 | Iteration 3 |
132 | 0!=0 ↓ 0(False) | - | - | - | - | - | - | While loop stops working as temp!=0 is evaluated to 0(False) |
- At first value of temp is checked to see whether it is 0 or not.
- The condition temp!=0 will produce either 1(True) or 0(False) after evaluation.
- If it is 1(True), the statements written within while loop are executed and the loop continues to iterate till the condition is 1(True).
- If it is 0(False) then the statements written within while loop are not executed and the control goes to the statement written immediately after the loop.
Within while loop, at first the last digit is extracted from the value stored in temp by performing modulo division operation using the expression temp%10. Thus the expression temp%10Â will give the remainder after integer division which is the last digit of the value stored in temp and the result is stored in rem.Â
After that the value stored in rem is added with the value stored in sum and the result is stored in the same variable i.e. sum.Â
The value stored in temp is divided by 10 to remove the last digit of the value stored in it and the result is stored in the same variable i.e. temp.
Thus the above process is used to find the sum of the digits present in the given number.
The final result is stored in sum.Â
Finally the sum of the digits present in the entered integer value along with the value is displayed on the output screen.