#include <iostream>
using namespace std;
int main()
{
int a;
int b = 0;
cout << " Enter a number : ";
cin >> a;
while ( a > 0 ) {
b =b+ a % 10;
a= a/ 10;
}
cout << "Sum = " << b;
return 0;
}
this code calculates sum of the digits of a number.
Even though I know it works I have a question that I cannot understand
for example if I write in cin that the number is 14.
than b=0+4=4 and a=14/10=1
and if the sum is b and b= 5, how is that my answer is still 5?
Last edited on
Thank you now I get everything you are the best:)) I am just beginning to study c++, so I have really big problems understanding some of it! thanks!!
so that means when I put 121
b=0
b=b+a%10
0=0+remainder of (121/10)
0=0+1
b=b+a%10
b=b+remainder of (120/10)
1=1+12=13
but the sum actually should be 4. So why is it 13?
121
b = b + Remainder of 121 / 10 | b = b + 1
b = b + Remainder of 12 / 10 | b = b + 2
b = b + remainder of 1 / 10 | b = b + 1
b = 4
You can never have a remainder > 10 if you are dividing by 10!
If you want to see program output, just put cout << a << "\n"; before the equations.
1 2 3
|
cout << a << "\n";
b =b+ a % 10;
a= a/ 10;
|
Last edited on
okay I get it now :)))))))) thanks!!!