0

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;
 }
2
  • 1
    x is divided by 10 in each loop. This is equivalent to shifting the decimal mumber one place to the right, and the loop stops when there is nothing left. Notice the pattern of the output - it is the number in reverse order. Commented Feb 16, 2019 at 18:52
  • regarding: x = x /10; this is an integer divide. In such a divide, all fractions are dropped. so the results of that divide are: 102, 10, 0 the modulo results are 1023%10= 3, 102%10= 2, 10%10= 0, etc Commented Feb 17, 2019 at 9:58

2 Answers 2

1

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).

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.