PLEASE EXPLAIN TO ME WHY DOES THIS HAPPEN

Write your question here.

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




if I write in 155 I do not get why I have the output 11.
because b=b+a%10= 0+155%10=5
5=5+150/10=5+15=20

I know that code is right but I do not get the logic can someone explain it for me in details??
1
2
3
4
5
6
Iteration 1:
b = 0 + 155%10 = 5.
Iteration 2:
b = 5 + 15%10 = 10.
Iteration 3:
b = 10 + 1%10 = 11.


Remember x = r; is not an equation, but an assignment command in programming. You are commanding the computer to make x equal to r.
and for what do I need declaring that a=a/10 ?
By making a = a/10, you are iteratively removing the last digit from a.

If a is initially 5456, then
1
2
3
4
5
6
7
8
after Iteration 1:
a = 5456 / 10 = 545
after Iteration 2:
a = 545 / 10 = 54
after Iteration 3:
a = 54 / 10 = 5
after Iteration 4:
a = 5 / 10 = 0

Topic archived. No new replies allowed.