Modulo Operations in Programming With Negative Results | Java 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
class GFG { static int truncMod ( int a , int n ) { int q = a / n ; return a - n * q ; } public static void main ( String [ ] args ) { int a , b ; a = 9 ; b = 4 ; System . out . println ( a + " ▁ % ▁ " + b + " ▁ = ▁ " + truncMod ( a , b ) ) ; a = - 9 ; b = 4 ; System . out . println ( a + " ▁ % ▁ " + b + " ▁ = ▁ " + truncMod ( a , b ) ) ; a = 9 ; b = - 4 ; System . out . println ( a + " ▁ % ▁ " + b + " ▁ = ▁ " + truncMod ( a , b ) ) ; a = - 9 ; b = - 4 ; System . out . println ( a + " ▁ % ▁ " + b + " ▁ = ▁ " + truncMod ( a , b ) ) ; } }