Modulus on Negative Numbers

What will be the output of the following C program?

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <stdio.h>
int main()
{
   int a = 3, b = -8, c = 2;
   printf("%d", a % b / c);
   return 0;
}

chevron_right


Output

1

% and / have same precedence and left to right associativity. So % is performed first which results in 3 and / is performed next resulting in 1. The emphasis is, sign of left operand is appended to result in case of modulus operator in C.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <stdio.h>
int main()
{
   // a positive and b negative.
   int a = 3, b = -8;
   printf("%d", a % b);
   return 0;
}

chevron_right


Output

3
filter_none

edit
close

play_arrow

link
brightness_4
code

#include <stdio.h>
int main()
{
   // a negative and b positive
   int a = -3, b = 8;
   printf("%d", a % b);
   return 0;
}

chevron_right


Output



-3
filter_none

edit
close

play_arrow

link
brightness_4
code

#include <stdio.h>
int main()
{
   // a and b both negative
   int a = -3, b = -8;
   printf("%d", a % b);
   return 0;
}

chevron_right


Output

-3

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Improved By : sushantgundla

Article Tags :
Practice Tags :


12


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.