AP® Computer Science Principles · Big Idea 3 · Topic 3.3
The MOD Operator
MOD gives the remainder left over after division. It turns any counting number into a value that cycles within a fixed range, instead of growing forever.
Division splits a number into a quotient and a remainder. MOD just keeps the remainder and throws away the quotient. Any number divided by 2 leaves a remainder of 0 or 1 - remainder 0 means it split evenly, so the number is even; remainder 1 means one is left over, so it's odd. That's why n MOD 2 is the classic even-odd test.
The useful trick is what happens as a counter grows. Picture a clock face with 5 positions, numbered 0 through 4. Counting up by 1 each time and taking MOD 5 sends you 0, 1, 2, 3, 4, then back to 0, then 1 again - the count keeps climbing underneath, but MOD 5 keeps reporting where you'd land on that 5-slot dial. The remainder can never reach the divisor itself; it resets to 0 right when the count would hit a multiple of it.
This is exactly how programs keep a growing index inside a fixed-length list. If a list has 5 slots (valid indexes 0 to 4) and a loop counter keeps climbing past 4, writing index MOD 5 instead of index keeps feeding the list a legal position every time, wrapping 5 back to 0, 6 back to 1, and so on. MOD shows up constantly alongside loops and lists: anywhere a counter needs to repeat a fixed cycle instead of running off the end, MOD is the tool.
Key terms
- MOD
- An operator that returns the remainder left over after dividing one number by another.
- Quotient
- The whole number of times a divisor fits into a number, not counting the remainder.
- Remainder
- What's left over after dividing as many whole times as possible; always less than the divisor.
- Wraparound
- Using MOD to send a growing count back to 0 once it reaches the divisor, forming a repeating cycle.
Watch it explained
- How it worksHow does MOD wrap a growing counter back around to the start like a clock face?
- Worked exampleFind the value of 17 MOD 5 and show the division that produces it.
- Worked exampleFind what n MOD 3 evaluates to for n running from 0 up to 9.
- Going furtherWhat happens to a program that uses MOD to cycle a list index past the end of the list?
Check yourself
End of topic.