- How to peel off digits with
n % 10and reduce the number withn /= 10 - Why
do-whileis the natural choice here — and how it handles zero without a special case - How to update a running maximum without accidentally printing intermediate results
- Why initialising the maximum to 0 works, and what a safer choice looks like
- How the same skeleton extends to smallest-digit, product-of-digits, and Armstrong check programs
Why Do-While Fits This Problem
There's one digit we have to be careful about — zero. If the input is 0, then there's exactly one digit to inspect, and it's a zero. A while loop that checks "n != 0" before the body runs would skip the digit entirely and never look at the input. A do-while loop, on the other hand, runs the body before checking the condition — so it always inspects at least one digit. That's the exact behaviour we want.
For inputs other than zero, both while and do-while produce the same answer. The difference only shows up at zero. And since zero is a valid integer with one digit (the digit is 0 itself), "handle zero correctly" isn't a nice-to-have — it's part of the spec. Using do-while means the code handles it naturally, without an explicit if checking for zero first.
This is also a good example of a broader lesson: choose the loop that matches the problem, not the one that's most familiar. For "extract every digit", the loop has to run at least once, because every integer has at least one digit. That "at least once" requirement is the signal for do-while. When you spot it, use it.
💡 In one line: every integer has at least one digit, so the loop must run at least once — that's the case do-while was made for.
Extracting Digits and Tracking the Max
The algorithm has three moving parts:
- Extract the last digit with
n % 10. For 45298, that's 8. - Compare it to the maximum so far and update the maximum if the new digit is bigger.
- Remove the last digit with
n = n / 10. For 45298, that becomes 4529.
Repeat until n reaches 0. The maximum has been updated once per digit, so it holds the largest one by the end.
| Iteration | n | n % 10 | max after update | n after n/10 |
|---|---|---|---|---|
| Start | 45298 | — | 0 | — |
| 1 | 45298 | 8 | 8 | 4529 |
| 2 | 4529 | 9 | 9 | 452 |
| 3 | 452 | 2 | 9 | 45 |
| 4 | 45 | 5 | 9 | 4 |
| 5 | 4 | 4 | 9 | 0 |
| Exit | 0 | — | 9 | — |
Notice that the maximum only updated twice — at iteration 1 (with digit 8) and at iteration 2 (with digit 9). After that, no subsequent digit beat 9, so the maximum stayed at 9. That's the usual behaviour — the max usually stabilises after the first few iterations.
Complete C Program
Program: find the largest digit using a do-while loop
#include <stdio.h>
int main(void) {
int n;
printf("Enter an integer: ");
if (scanf("%d", &n) != 1) {
printf("Invalid input.\n");
return 1;
}
/* Digit extraction only cares about magnitude, not sign */
if (n < 0) n = -n;
/* Start at 0 — every digit is at least 0, so this is a safe lower bound.
To be extra defensive, -1 would also work. */
int max = 0;
do {
int digit = n % 10; /* extract the last digit */
if (digit > max) max = digit; /* track the largest seen */
n = n / 10; /* remove the last digit */
} while (n != 0);
printf("Largest digit = %d\n", max);
return 0;
}
And here's the same logic with a while loop, for comparison. Notice the extra zero check — without it, the loop never runs for input 0 and reports the initial max (0) as the answer, which is technically correct but for the wrong reason:
Same program with a while loop — note the extra zero handling
#include <stdio.h>
int main(void) {
int n;
printf("Enter an integer: ");
scanf("%d", &n);
if (n < 0) n = -n;
if (n == 0) {
printf("Largest digit = 0\n");
return 0;
}
int max = 0;
while (n > 0) {
int digit = n % 10;
if (digit > max) max = digit;
n = n / 10;
}
printf("Largest digit = %d\n", max);
return 0;
}
Both versions produce identical results, including for zero. But the do-while version has one fewer branch — one less thing to remember. When the logic naturally fits "at least once", do-while removes a whole class of edge-case checks. That's why the assignment asks for it.
Program Output
Enter an integer: 45298
Largest digit = 9
A few more to try. Input 0 and you should get 0 — the do-while version handles this without any special case. Input 7 and you should get 7 (single digit). Input 10000 and you should get 1 (all the other digits are zeros). Input -903 and you should get 9 — the minus sign isn't a digit, so the absolute value is what matters. Input 9999999 and you should also get 9 — every digit is the max, and the loop correctly reports it after examining all seven.
Step-by-Step Explanation
Let's walk through 45298, then look at the subtleties.
1. Reading and normalising input
scanf reads the integer, and the if (n < 0) n = -n; line takes absolute values. For −45298, this becomes 45298. The digit extraction loop then behaves exactly as it would for a positive input. Without this, the modulo operation n % 10 on a negative number would produce negative results in C (−45298 % 10 = −8 in C), and the comparison digit > max would always be false — the loop would report 0, which is wrong.
2. Initialising max to 0
Digits are 0 through 9. Starting max at 0 means the first extracted digit (which is at least 0) can always compare against it. If the input were only zeros (say 0 or 10000), max would stay 0, which is correct — the largest digit is 0. Starting at -1 would work too and would be marginally more defensive (a digit of 0 would update it to 0), but the initial value of 0 is simpler and produces the same answer.
What you should not do is start max at something arbitrary like 9 or 100. If the input happened to have digits all smaller than that, the initial value would dominate and the answer would be wrong. Start at the smallest possible digit (0, or -1 if you want to be paranoid about it).
3. The do-while body
Three lines execute on every iteration:
int digit = n % 10;— extract the last digit. For 45298, this is 8. For 4529, this is 9. And so on.if (digit > max) max = digit;— update the maximum if the new digit beats the current one. This is the standard "running maximum" pattern.n = n / 10;— remove the last digit. This shrinks the number and is what makes the loop terminate.
After the body, the condition n != 0 is checked. If n reached 0 (meaning we've processed all digits), the loop exits. Otherwise, it iterates again.
4. The trace for 45298
Here's the loop state after each iteration:
- Start:
n = 45298,max = 0 - Iteration 1:
digit = 8,max = 8,n = 4529 - Iteration 2:
digit = 9,max = 9,n = 452 - Iteration 3:
digit = 2,max = 9(unchanged),n = 45 - Iteration 4:
digit = 5,max = 9,n = 4 - Iteration 5:
digit = 4,max = 9,n = 0 - Condition fails:
n != 0is false → exit
Final answer: 9.
5. Why the do-while eliminates the zero special case
The classic bug in this kind of program is: for input 0, a while (n > 0) loop never runs — n is already 0, so the condition is false on entry. The program reports max = 0, which happens to be correct by accident, but only because we initialised max to 0. If we'd initialised max to -1 (a more defensive choice), the loop would return -1 for input 0 — wrong. The do-while avoids this because the body runs before the condition is checked. For n = 0, it extracts digit 0, updates max (0 > 0 is false, so no update), then n = 0/10 = 0, condition fails, exit. Final answer: 0. Correct, without any special case.
6. Why the loop always terminates
Same reason as the digit-counting program. n = n / 10 strictly decreases n for positive n. A strictly decreasing sequence of non-negative integers must reach 0 in finitely many steps. So the loop terminates — and it terminates after exactly as many iterations as there are digits.
7. The running maximum pattern
This exact pattern — "start at a lower bound, then update whenever you find something bigger" — shows up everywhere. Finding the largest element in an array, the maximum in a stream of numbers, the highest score in a game, the longest line in a file. Once you can write it inside a digit-extraction loop, you can write it for any other context. It's one of the most reusable patterns in programming.
🎯 Remember this: extract the last digit with n % 10, compare to max, update if bigger, then shrink n with n /= 10. Use do-while so the loop runs at least once — that's what makes zero just work, without a special case.
Frequently Asked Questions
1. Why does the assignment ask for do-while specifically?
Because the do-while naturally fits the problem: every integer has at least one digit, so the body must run at least once. A while loop would require an extra check for the zero case, which adds noise. The do-while version is shorter, more elegant, and handles zero without any special case. That's the kind of fit between problem and tool that makes code readable.
2. What if the input has a zero at the front — like "0234"?
That's not how C reads integers. When you enter "0234" as an int, C reads it as decimal 234. Leading zeros in an integer literal aren't stored — they're just a display convention. If you genuinely need to preserve leading zeros (like in a phone number or a PIN), store the input as a string, not as an int. For the largest-digit problem, the input is treated as a number, so leading zeros are simply ignored — the largest digit of "0234" is 4, and the largest digit of 234 is also 4.
3. Why not just use a for loop from 0 to 9 and check if each digit appears?
You could — for each digit d from 9 down to 0, check if the original number contains d. The first d that does appear is the answer. That's ten passes over the number (or one pass if you use a boolean array to record which digits you've seen). The digit-extraction approach is simpler and does one pass, so it's both faster and easier to read. The only reason to use the digit-check approach is if you also need to know which digits appear — but that's a different problem.
4. What about finding the smallest digit — how does it differ?
The pattern is almost identical: extract each digit, compare to min, update if smaller. But you need a different starting value. Starting min at 0 would be wrong — no digit is smaller than 0, so min would stay 0 and you'd always report 0. Start min at 9 (the largest possible digit), and the first extracted digit will always be smaller than or equal to 9 — so min gets updated on the first iteration and stays small. Or start at a very large value like INT_MAX to be safe. That's the symmetric difference between the largest-digit and smallest-digit programs — everything else is the same.
5. Can I extend this to find the second largest digit?
Yes, with a small modification: track two variables, max and second_max. For each digit, if it beats max, shift max into second_max and update max. If it's less than max but beats second_max, update second_max only. It's a bit more code, but the pattern is the same — you're just tracking two running values instead of one. Interviewers love this variation, because it catches candidates who only memorised the single-max version.
6. What happens with a negative input like −903?
Without the if (n < 0) n = -n; line, n % 10 on −903 would give −3 in C (C's modulo keeps the sign of the left operand). That would fail the comparison digit > max (since −3 < 0), so the digit 3 would never be considered. The maximum would incorrectly end up as 0. Taking the absolute value first — the magnitude is what we care about — sidesteps this entirely. And the result is the same as for 903: largest digit 9.
💡 Tip: Once this program clicks, try modifying it to also report which position the largest digit is in (counting from the left, or from the right). That's a slightly harder problem — you have to track both the digit and its position — but it reinforces that the extraction loop gives you access to everything you need. Then look at the smallest-digit program (assignment 8), which uses exactly the same skeleton with a flipped comparison and a different starting value.