Unit 1 Cycle 1 Day 5: Modulo and Integer Division
Share
Modulo and Integer Division
Section 1.3 — Expressions and Assignment
Key Concept
The modulo operator (%) returns the remainder after division and is one of the most tested concepts on the AP CSA exam. For example, 17 % 5 produces 2 because 17 divided by 5 is 3 with a remainder of 2. Combined with integer division (/), you can extract individual digits from a number: n % 10 gives the last digit, while n / 10 removes the last digit. Watch for negative operands — Java's modulo result takes the sign of the dividend.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (A) 5 hours 17 minutes
This is a classic time conversion pattern:
hours: 317 / 60 = 5 (integer division drops remainder).
mins: 317 % 60 = 17 (remainder after dividing by 60, since 5 * 60 = 300 and 317 - 300 = 17).
Output: 5 hours 17 minutes
Why Not the Others?
(B) Integer division never produces a decimal. 317 / 60 with both int operands gives 5, not 5.28.
(C) 27 is incorrect for the remainder. 317 % 60: find how many times 60 fits into 317 (5 times = 300), then subtract: 317 - 300 = 17.
(D) The modulo operator always returns an integer when both operands are integers. It gives the whole-number remainder, not a decimal.
Common Mistake
To compute %, students should think: how many times does 60 fit evenly into 317? That is 5 times (300). The remainder is 317 - 300 = 17. A common error is confusing / (quotient) with % (remainder).
AP Exam Tip
The / and % pair is extremely common on the AP exam for extracting digits, converting units, and cycling through ranges. Always remember: a / b gives the quotient and a % b gives the remainder.