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 : The AP exam focuses on non-negative operands, but knowing this avoids surprises. Modulus only works with integer types in AP CSA, applying it to typical int values produces an int remainder. Master % and a huge family of problems (digit manipulation, cycles, parity checks) becomes straightforward.
Challenge: Split Into Tens and Ones