Home > Back-end >  why does 1%2 return 1 in C but not 0
why does 1%2 return 1 in C but not 0

Time:12-16

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.

CodePudding user response:

When talking about remainders, we're obviously talking about integer division. In C, this is truncating division.

1 divided by 2 is 1 / 2 with a remainder of 1 % 2.
1 / 2 is 0, so 1 % 2 must be 1 (since 0 * 2 1 = 1).


More examples,

24 divided 10 is 24 / 10 with a remainder of 24 % 10.
24 / 10 is 2, so 24 % 10 must be 4 (since 2 * 10 4 = 24).

-24 divided 10 is -24 / 10 with a remainder of -24 % 10.
-24 / 10 is -2, so -24 % 10 must be -4 (since -2 * 10 -4 = -24).

Different languages handle negative numbers differently. Again, C uses truncating division.

CodePudding user response:

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.

  •  Tags:  
  • c
  • Related