1

I'm learning C basics right now. I have a question which is confusing me little bit.
My question is how the below program's output is - 2 ?

  #include<stdio.h>
    int main()
   {
    printf("%d", -5%3);
    return 0 ;
   }
  • 2
    That's not programing, it's maths... – Thomas Ayoub Jun 17 '15 at 06:51
  • 1
    Depending on which `C` standard you are compiling your program with using the `%` or `\` with negative numbers gives you different results. In The `C89` standard it is stated that if either operand should be negative the result of a division or modulo can be rounded up or down. So `-5 \ 3` could either be `-1` or `-2`. For the case of `%` if any of the two numbers `x` and `y` is negative the sign of `x % y` is implementation dependent in `C89`. In `C99` the result of a division is truncated towards zero. That means `-5 \ 3` is `-1` and `-5 % 3` is `-2`. – lord.garbage Jun 17 '15 at 06:59

1 Answers1

1

The % operator is gives you the remainder left after of integer division. Then -5/3 = -1 with -2 as remainder of division as 3*(-1)=-3 and -5-(-3)=-5+3=-2.

Kunal Saini
  • 138
  • 10
LPs
  • 16,045
  • 8
  • 30
  • 61