Loop Assignment 7 — Find the Largest Digit Using Do-While Loop
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Find the Largest Digit in an Integer Using a Do-While Loop

📑 On this page:
  • Why Do-While Fits This Problem
  • Extracting Digits and Tracking the Max
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to peel off digits with n % 10 and reduce the number with n /= 10
  • Why do-while is 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.

Diagram showing the digits of 45298 extracted one at a time, with 9 highlighted as the largest

Extracting Digits and Tracking the Max

The algorithm has three moving parts:

  1. Extract the last digit with n % 10. For 45298, that's 8.
  2. Compare it to the maximum so far and update the maximum if the new digit is bigger.
  3. 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
Start45298—0—
145298884529
2452999452
34522945
445594
54490
Exit0—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:

  1. int digit = n % 10; — extract the last digit. For 45298, this is 8. For 4529, this is 9. And so on.
  2. if (digit > max) max = digit; — update the maximum if the new digit beats the current one. This is the standard "running maximum" pattern.
  3. 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:

  1. Start: n = 45298, max = 0
  2. Iteration 1: digit = 8, max = 8, n = 4529
  3. Iteration 2: digit = 9, max = 9, n = 452
  4. Iteration 3: digit = 2, max = 9 (unchanged), n = 45
  5. Iteration 4: digit = 5, max = 9, n = 4
  6. Iteration 5: digit = 4, max = 9, n = 0
  7. Condition fails: n != 0 is 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.

📖 Related Tutorials

  • 6. Count the Digits in an Integer Using a While Loop
  • 8. Find the Smallest Digit in an Integer Using a While Loop
  • 9. Count the Occurrences of a Specific Digit Using a For Loop
  • 10. Calculate the Product of All Digits Using a While Loop
  • 12. Output Digits in Reverse Order Using a While Loop
  • Do-while Loop
  • While Loop
  • All 30 Loop Assignments

Previous Topic: -->> 6. Count the Digits in an Integer Using a While Loop   ||   Next Topic: -->> 8. Find the Smallest Digit in an Integer Using a While Loop


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.