Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Modulus on Negative Numbers

  • Difficulty Level : Easy
  • Last Updated : 28 Aug, 2021

What will be the output of the following C program? 
 

Take a step-up from those "Hello World" programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.

c




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

C++




#include <iostream>
using namespace std;
 
int main() {
 
   int a = 3, b = -8, c = 2;
   cout << a % b / c;
   return 0;
}
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.
 

c




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

C++




#include <iostream>
using namespace std;
 
int main() {
     int a = 3, b = -8;
     cout << a % b;
    return 0;
}

Output 



3

 

c




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

C++




#include <iostream>
using namespace std;
 
int main()
{
   // a negative and b positive
   int a = -3, b = 8;
   cout << a%b;
   return 0;
}

Output 

-3

 

c




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

C++




#include <iostream>
using namespace std;
 
int main() {
   // a and b both negative
   int a = -3, b = -8;
   cout << a % b;
   return 0;
}

Output 

-3

Anyone can predict the output of a modulus operator when the both operands are positive. But when it comes to the negative numbers, different languages give different outputs.

In C language, modulus is calculated as,

a % n = a – ( n * trunc( a/n ) ).

For example,
8 % -3 = 8 – ( -3 * trunc(8/-3) )
           = 8 – ( -3 * trunc(-2.666..) )
           = 8 – ( -3 * -2 ) { rounded towards zero }
           = 8 – 6
           = 2

For more info, please see https://en.wikipedia.org/wiki/Modulo_operation

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :