Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Smita Kapse

Here we will see what will be the result if we use negative numbers to get the modulus. Let us see the following programs and their outputs to get the idea.

Example

#include<stdio.h>
int main() {
   int a = 7, b = -10, c = 2;
   printf("Result: %d", a % b / c);
}

Output

Result: 3

Here the precedence of % and / are same. So % is working at first, so a % b is generating 7, now after dividing it by c, it is generating 3. Here for a % b, the sign of left operand is appended to the result. Let us see it more clearly.

Example

#include<stdio.h>
int main() {
   int a = 7, b = -10;
   printf("Result: %d", a % b);
}

Output

Result: 7

If we interchange the sign of a and b, then it will be like below.

Example

#include<stdio.h>
int main() {
   int a = -7, b = 10;
   printf("Result: %d", a % b);
}

Output

Result: -7

Similarly if both are negative, then also the result will be negative.

Example

#include<stdio.h>
int main() {
   int a = -7, b = -10;
   printf("Result: %d", a % b);
}

Output

Result: -7

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.