PROGRAMMING FUNDAMENTALS › JAVA FUNDAMENTALS
For temp = 1221, the expression temp % 10 selects the rightmost digit, while temp / 10 removes that digit through integer division. Repeating both operations processes the number from right to left. The digits appear as 1, 2, 2, and 1, then temp becomes 0 and the loop stops.
int temp = 1221;
while (temp > 0) {
int digit = temp % 10;
temp = temp / 10;
}| CURRENT TEMP | DIGIT = TEMP % 10 | NEXT TEMP = TEMP / 10 |
|---|---|---|
| 1221 | 1 | 122 |
| 122 | 2 | 12 |
| 12 | 2 | 1 |
| 1 | 1 | 0 |
Given temp = 1221, which pair produces digit = 1 and next temp = 122?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
Store 1221 in original, then copy it into temp. The loop changes temp from 1221 to 122, then 12, then 1, and finally 0. The value in original never changes, so it remains available after every digit has been processed.
int original = 1221;
int temp = original;
while (temp > 0) {
int digit = temp % 10;
temp = temp / 10;
}
// original is still 1221, while temp is 0If you divide original directly inside the loop, original eventually becomes 0. That is useful for stopping the loop, but it leaves no copy of 1221 for a later comparison. A palindrome test that needs the original value must preserve it before the loop starts.
The same extracted digit can update several accumulators. Add 1 to count for every pass, add digit to sum, and place digit into reversed. The loop does not need a new structure for each task. Only the update applied after extraction changes.
int count = 0;
int sum = 0;
int reversed = 0;
int temp = 1221;
while (temp > 0) {
int digit = temp % 10;
count = count + 1;
sum = sum + digit;
reversed = reversed * 10 + digit;
temp = temp / 10;
}| DIGIT | COUNT | SUM | REVERSED |
|---|---|---|---|
| 1 | 1 | 1 | 1 |
| 2 | 2 | 3 | 12 |
| 2 | 3 | 5 | 122 |
| 1 | 4 | 6 | 1221 |
Complete the reverse update for the digits of 1221.
reversed = reversed * 10 + ____;Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
After the loop finishes, temp is 0 but reversed contains the complete number in reverse order. Compare reversed with original only then. For 1221, both values are 1221, so the number is a palindrome.
int original = 1221;
int temp = original;
int reversed = 0;
while (temp > 0) {
int digit = temp % 10;
reversed = reversed * 10 + digit;
temp = temp / 10;
}
if (reversed == original) {
System.out.println("1221 is a palindrome");
} else {
System.out.println("1221 is not a palindrome");
}Comparing reversed with the consumed value of original is a different operation: after direct division, that value is 0. The comparison then rejects 1221 even though its reverse is 1221. Matching the first and last digits alone is also not enough, because the middle digits still need to be processed before the decision is complete.