/*The operator $%$ is used to compute the remainder $a%b$ of dividing an integer $a$ modulo (by) a non-zero integer $b$. you might have seen early in school things like "17 divided by 5 is 3 remainder 2", perhaps written "3 r 2". the remainder 2 is what "17 mod 5" or $17%5$ computes. examples: 17 divided by 5 3 remainder 2 17/5 is 3, 17%5 is 2 15 divided by 5 3 remainder 0 15/5 is 3, 15%5 is 0 0 divided by 5 0 remainder 0 0/5 is 0, 0%5 is 0 3 divided by 5 0 remainder 3 3/5 is 0, 3%5 is 3 */ public class modop { public static void main(String[] args) { int a,b,rem; System.out.println("Calculating Remainder: a%b"); //Try some values a=17;b=5; System.out.println(a+" mod "+ b+ " is " + a%b); a=0;b=3; System.out.println(a+" mod "+ b+ " is " + a%b); // What happens with negative numbers? // Try negative numbers a=17;b=-3; System.out.println(a+" mod "+ b+ " is " + a%b); a=-17;b=3; System.out.println(a+" mod "+ b+ " is " + a%b); // Observe that the remainder always takes the sign of the numerator /* Before we answer, recall that this course is primarily an introduction to programming, not an introduction to java. thus, let us consider a more generally useful question -- what MAY happen in TYPICAL programming languages? answer 1: if the remainder is 0, there is nothing unexpected: -15 divided by 5 -3 remainder 0 -15/5 is -3, -15%5 is 0 answer 2: if the remainder is non-zero, it could be EITHER positive or negative -- you should write code that works in either case: -17 divided by 5 is either -3 remainder -2 -17/5 is -3 and -17%5 is -2 or -4 remainder 3 -17/5 is -4 and -17/5 is 3 usually, we want a non-negative remainder, so code like this is what we use: */ // To obtain a non-negative remainder of a modulo b rem = a % b; if (rem < 0) rem = rem + b; System.out.println(a+" mod "+ b+ " is " + rem); } //method main } //class modop