The Modulus Operator

Part of: Primitive Types

What Modulus Computes. The modulus operator % returns the remainder after integer division. While / gives the quotient, % gives what is left over. A helpful identity: for positive ints, a == (a / b) b + (a % b). The quotient and remainder fit back together perfectly. Extremely Common Uses. Modulus is one of the most useful operators in all of programming: - Even or odd : n % 2 == 0 is true exactly when n is even. - Divisibility : n % k == 0 means n is divisible by k. - Last digit : n % 10 extracts the ones digit of a number. - Wrapping / cycling : (i + 1) % size cycles an index back to 0. Combining / and %. Together, / and % let you break a number apart: This pattern converts a count of pennies into dollars and cents, or seconds into minutes and seconds. Behavior with Negatives. In Java, the result of % takes the sign of the left operand : What usually goes wrong. What you see What caused it How to fix it --- --- --- Input 47 prints 7 then 4 The remainder was printed before the quotient n / 10 is the tens digit and n % 10 is the ones digit, in that order Both lines print the same digit The same operator was used twice One line uses /, the other uses % Input 9 prints nothing on the

Challenge: Split Into Tens and Ones