Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why does 1%2 return 1 in C but not 0

int i = 1;
printf("%d",i % 2);

the above code snippet outputs 1. the modulo or remainder operator returns the remainder of a division but 1/2 is 0.5 and there’s no remainder here. that’s what i think

I was expecting an output of 0.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your question has nothing to do with the printing nor with type casting.

Modulo is simply the remainder of the operation of division between two integers.

When you want to calculate 1%2 (or any modulo), the logic goes like this:

  • How many times does 2 fit into 1?
  • The answer is 0 times, as it 2 > 1
  • So, after fitting 2 zero times in 1, the remainder is still 1.

It might help to consider another example. Let’s say 2%1. In this case,
we can fit perfectly fit 1 two times into 2, and, in this case, the remainder will be 0.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading