Modulo Operations in Programming With Negative Results | C ++ 14 program to illustrate modulo operations using the above equation ; Function to calculate and return the remainder of a % n ; ( a / n ) implicitly gives the truncated result ; Driver Code ; Modulo of two positive numbers ; Modulo of a negative number by a positive number ; Modulo of a positive number by a negative number ; Modulo of two negative numbers
#include <bits/stdc++.h> NEW_LINE using namespace std ; int truncMod ( int a , int n ) { int q = a / n ; return a - n * q ; } int main ( ) { int a , b ; a = 9 ; b = 4 ; cout << a << " ▁ % ▁ " << b << " ▁ = ▁ " << truncMod ( a , b ) << endl ; a = -9 ; b = 4 ; cout << a << " ▁ % ▁ " << b << " ▁ = ▁ " << truncMod ( a , b ) << endl ; a = 9 ; b = -4 ; cout << a << " ▁ % ▁ " << b << " ▁ = ▁ " << truncMod ( a , b ) << endl ; a = -9 ; b = -4 ; cout << a << " ▁ % ▁ " << b << " ▁ = ▁ " << truncMod ( a , b ) << endl ; }