Reputation: 3
I ran it through an IDE and the remainder values came out 3, 2, 0, 1. I understand the first remainder, but not the rest. Also, how come the loop terminates? Isn't x always going to be greater than 0, therefore continuing indefinitely? Thank you.
int x = 1023;
while (x > 0)
{
printf("%d", x% 10);
x = x /10;
}
Upvotes: 0
Views: 54
Reputation: 72463
Note that in C, when both operands of a division have integer type, the division also has an integer type, and the value is the result of division rounded toward zero.
So in the first iteration, the statement x = x /10;
changes x
from 1023
to 102
(not 102.3
).
Upvotes: 1
Reputation: 66
since you are dividing integers you are getting rounded results each time,
so each iteration of x becomes
102
10
1
Just print x each time and you will see. So 102 modulo 10 is 2
10 modul0 10 is 0
1 modulo 10 is 1
Upvotes: 0