AP® Computer Science A · Unit 2 · Topic 2.9
Digit Algorithms with Division and Mod
Dividing an integer by 10 and taking it mod 10 strips off one digit at a time, because mod 10 keeps the ones place and integer division drops it. Looping this peels a number apart digit by digit.
Integer division and mod are opposites that split a number into two pieces at the ones place. n % 10 throws away everything except the last digit. n / 10, using integer division, throws away the last digit and keeps everything else, shifted one place to the right. Do both to the same n and you've separated it into "last digit" and "everything before it" with no string methods, no arrays, just arithmetic.
A digit-extraction loop repeats that split: grab n % 10, do something with it (add it to a sum, append it to a reversed number, count it), then reassign n = n / 10 so the number is one digit shorter. Keep going while n > 0, and each pass exposes a new rightmost digit, moving from ones to tens to hundreds. The loop ends naturally once n has been divided down to 0, because there are no digits left to peel.
This sits right next to counter-controlled and sentinel-controlled loops in the unit: the digit loop is really a sentinel loop where the sentinel is n reaching 0, and the number of passes depends on how many digits n has rather than a count you set in advance. It's also a clean place to watch a trace table fill in, since n, the extracted digit, and a running result (sum, reversed number, digit count) all change together on every single pass.
Key terms
- Integer division
- Division between integers that truncates toward zero and drops any remainder, like n / 10 in Java.
- Modulo (%)
- The remainder operator; n % 10 gives whatever integer division by 10 would discard.
- Digit extraction
- Using % 10 to read the last digit and / 10 to remove it, repeated until the number reaches 0.
- Sentinel-controlled loop
- A loop that keeps running until a specific value, here n becoming 0, signals it to stop.
Watch it explained
- How it worksHow does dividing by 10 and taking mod 10 peel exactly one digit off per pass?
- Worked exampleTrace a loop that sums the digits of 4729 and find the total after every pass.
- Worked exampleFind what a loop that builds a reversed number out of 1230 produces.
- Common mistakeWhy doesn't a while (n > 0) digit loop give the right answer when n starts at 0?
Check yourself
End of topic.