Modulo Operator for Negative Operands
The sign of the result for the modulo operator is machine-dependent for negative operands, as the action takes as a result of underflow or overflow.
Example 2: C/C++ program to demonstrate the modulo operator for negative operands.
C++
// C++ Program to demonstrate the working of the modulo // operator for negative operands #include <iostream> using namespace std; // Driver code int main( void ) { int x, y; int result; x = -3; y = 4; // modulo for negative operands result = x % y; cout << result << endl; x = 4; y = -2; result = x % y; cout << result << endl; x = -3; y = -4; result = x % y; cout << result; return 0; } // This code is contributed by Harshit Srivastava |
C
// C Program to illustrate the working of the modulo // operator with negative operands #include <stdio.h> int main( void ) { int x, y; int result; x = -3; y = 4; // modulo for negative operands result = x % y; printf ( "%d" , result); x = 4; y = -2; result = x % y; printf ( "\n%d" , result); x = -3; y = -4; result = x % y; printf ( "\n%d" , result); return 0; } |
-3 0 -3
Note: The return value in this case is compiler dependent.
Modulo Operator (%) in C/C++ with Examples
In C or C++, the modulo operator (also known as the modulus operator), denoted by %, is an arithmetic operator. The modulo division operator produces the remainder of an integer division which is also called the modulus of the operation.