Loop Assignment 8 — Find the Smallest Digit Using While Loop
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Find the Smallest Digit in an Integer Using a While Loop

📑 On this page:
  • The Mirror Image of Largest-Digit
  • Why the Starting Value Matters
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • Why the initial value for min must be 9 (or higher) — and what happens if you get it wrong
  • How the extraction loop from the largest-digit program flips to give the smallest
  • Why zero is special, and how to handle it cleanly
  • How the running-minimum pattern differs from running-maximum
  • How this pattern generalises to "smallest element in an array" or "minimum in a stream"

The Mirror Image of Largest-Digit

If you've already done the largest-digit program, this one will feel familiar. The loop is the same. The extraction and shrinking steps are the same. Only two things change: the comparison operator (< instead of >) and the initial value of the accumulator. That's it. That's the whole diff.

But those two small changes have an outsized impact on whether the program works. The largest-digit program initialised max = 0, which works because every digit is at least 0. The smallest-digit program can't initialise min = 0 — because then no digit would ever be less than the initial value, and the loop would always report 0. Instead, min must start at the largest possible digit (9), so the first extracted digit always beats or ties it and updates it.

This is one of the most common beginner mistakes in minimum-finding code. The comparison operator feels obvious; the initial value is the thing that gets overlooked. In a lot of code review sessions, someone looks at a minimum-finder and says "why did you start min at zero?" — and the answer is usually "I copied the max-finder." The fix is one character, but the lesson is worth learning early.

💡 In one line: start the minimum at 9 — not 0 — because every digit must beat or tie it on the first iteration to be recorded.

Diagram showing the digits of 45298 extracted one at a time, with 2 highlighted as the smallest

Why the Starting Value Matters

The algorithm runs three steps per iteration:

  1. Extract the last digit with n % 10.
  2. Compare it to min; update min if it's smaller.
  3. Shrink the number with n = n / 10.

For 45298, the digits extracted in order are 8, 9, 2, 5, 4. The minimum after each iteration is:

Iteration n n % 10 min after update n after n/10
Start45298—9—
145298884529
2452998452
34522245
445524
54420
Exit0—2—

Compare to the largest-digit program: max stabilised immediately (after finding 9 at iteration 2), but min keeps updating — it found 8, then 2, and then never went lower. That's typical: minimums usually update in later iterations than maximums, because the smallest digit doesn't appear first as often.

Now consider what would happen if min started at 0. On every iteration, if (digit < 0) would fail — no digit is negative. So min would stay 0 forever. The program would report 0 as the smallest digit of 45298. That's obviously wrong, and it illustrates exactly why the starting value matters so much for a minimum-finder.

Complete C Program

Program: find the smallest digit using a 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;

    /* Zero is its own smallest digit — handle before the loop */
    if (n == 0) {
        printf("Smallest digit = 0\n");
        return 0;
    }

    /* Start at 9 — every digit is ≤ 9, so the first extracted digit
       will update min on the very first iteration */
    int min = 9;

    while (n > 0) {
        int digit = n % 10;          /* extract the last digit */
        if (digit < min) min = digit; /* track the smallest seen */
        n = n / 10;                  /* remove the last digit */
    }

    printf("Smallest digit = %d\n", min);
    return 0;
}
                                    

And here's the do-while variant, which eliminates the zero special case for the same reason as in the largest-digit program. The only thing to keep in mind is that min still starts at 9:

Do-while variant — no zero case needed

#include <stdio.h>

int main(void) {
    int n;
    printf("Enter an integer: ");
    scanf("%d", &n);

    if (n < 0) n = -n;

    int min = 9;
    do {
        int digit = n % 10;
        if (digit < min) min = digit;
        n = n / 10;
    } while (n != 0);

    printf("Smallest digit = %d\n", min);
    return 0;
}
                                    

Both versions produce the same result. The do-while one is shorter by two lines, at the cost of one subtle thing — that initial min = 9 must still be there, and it must be set correctly. So even in the compact version, the thing that really matters (the starting value) is unchanged.

Program Output

Enter an integer: 45298
Smallest digit = 2
                                

A few more to try. Input 0 and you should get 0. Input 7 and you should get 7. Input 10000 and you should get 0 — because it has four zeros, and 0 is always the smallest non-negative digit. Input -903 and you should get 0 (the digits are 9, 0, 3 after taking absolute value). Input 9999999 and you should get 9 — all digits are the same. Input 10 and you should get 0. And a tricky case: 2147483647 (the largest int) should give 1, because that's the smallest digit among the ten.

Step-by-Step Explanation

Let's walk through 45298 and then unpack the differences from the largest-digit version.

1. Input and absolute value

Same as before. Negative inputs need absolute-value treatment because C's modulo keeps the sign of the left operand: −45298 % 10 = −8, and −8 < min would never be true with min = 9. Absolute value first, then proceed.

2. The zero case

For n = 0, the smallest digit is 0 — obviously. But a while (n > 0) loop never runs, so min stays at its initial value. If we'd started at 9, the program would report 9, which is wrong. The explicit early return fixes this. Alternatively, the do-while variant runs the body once even for zero, extracts digit 0, compares 0 < 9 (true), updates min to 0, then shrinks n to 0 and exits. Either approach works.

3. Initialising min to 9

This is the most important line in the program. Every decimal digit is between 0 and 9, so starting at 9 guarantees that the first extracted digit will satisfy digit < min (or tie it). Tying is also fine — if the first digit is 9, 9 < 9 is false, but min is already correct (9), so the program still works.

What you must not do is start at 0, as discussed. What about starting at a huge value like INT_MAX? That works too, and it's a more "defensive" pattern — it doesn't depend on knowing that digits are bounded by 9. For a general minimum-finder over an array of arbitrary integers, starting at INT_MAX is often the right choice. For digit-finding, 9 is fine and clearer.

4. The main loop

For 45298, the loop runs five times:

  1. digit = 8, 8 < 9 → min = 8, n = 4529
  2. digit = 9, 9 < 8 false → min stays 8, n = 452
  3. digit = 2, 2 < 8 → min = 2, n = 45
  4. digit = 5, 5 < 2 false → min stays 2, n = 4
  5. digit = 4, 4 < 2 false → min stays 2, n = 0

Loop exits when n reaches 0. Final answer: 2.

5. Why the loop terminates

Same reasoning as everywhere else in this series: n = n / 10 strictly decreases n for positive n, and a strictly decreasing sequence of non-negative integers must reach 0 in finitely many steps. The loop terminates after exactly as many iterations as there are digits.

6. The running-minimum pattern

The comparison if (digit < min) min = digit; is the mirror of if (digit > max) max = digit; from the previous program. Both are instances of the "running extreme" pattern — track one value, update it whenever you see something better. The pattern generalises to any set of values: arrays, streams, file lines, sensor readings, whatever. The only thing that changes between min and max is the comparison operator and the initial value.

7. A subtle case: when all digits are 9

For an input like 999, the loop runs three times. On each iteration, digit = 9 and 9 < min is 9 < 9, which is false. So min stays at 9 the whole time — never updated. The final answer is 9, which is correct. This is an important edge case for minimum-finders: the initial value must be an upper bound that's "loose" enough that a tie (first digit equals initial value) is still correct. With min = 9, any input starting with 9 correctly reports 9 as the minimum if all subsequent digits are ≥ 9 (i.e., all are 9).

If we'd started at 8, input 999 would incorrectly report 9, but input 999 would have failed to update on the first iteration (9 < 8 is false) and the answer would be stuck at 8. That's why the initial value must be the true upper bound of the domain — not just any value greater than the first digit.

🎯 Remember this: the only difference from the largest-digit program is < instead of > and min = 9 instead of max = 0. Get those two right, and the loop is identical.

Frequently Asked Questions

1. Why does min start at 9 and not at 0?

Because every digit is between 0 and 9. Starting at 9 means the first extracted digit will satisfy digit < min or tie it, so the minimum gets set correctly from the start. Starting at 0 would be a bug: no digit is negative, so digit < 0 would always fail, and the loop would report 0 regardless of the actual input. If you're coming from the largest-digit program and just copied the code, this is the one line you have to change.

2. What if all the digits are the same, like 999 or 555?

The loop still works. For 999, the first iteration sees digit = 9, 9 < 9 is false, so min stays at 9. Every subsequent iteration also sees 9. Final answer: 9, which is correct. For 555, the first iteration sees 5, 5 < 9 is true, so min = 5. Subsequent iterations see 5, 5 < 5 is false, so min stays at 5. Final answer: 5. The one edge case worth tracing is the input 999 — but it checks out.

3. How is this different from finding the largest digit?

Three differences, and only one is superficial. First, < instead of > in the comparison — that's the superficial one. Second, min = 9 instead of max = 0 — that's the crucial one; get it wrong and the program silently returns the wrong answer. Third, the zero handling is more important here: for input 0, the smallest digit is 0 and the loop must not skip it. The largest-digit program also has this concern (max would incorrectly report 0 for input 0, but since the actual answer is 0, the bug is invisible); the smallest-digit program would report 9 for input 0 if the zero case weren't handled, which is a visible bug.

4. Could I use INT_MAX instead of 9 as the starting value?

Yes, and it would work. The advantage of INT_MAX is that it doesn't assume the domain — you could use the same pattern for finding the minimum of an array of arbitrary integers, where values might not be bounded by 9. The disadvantage is that it's slightly less obvious to a beginner reading the code ("why is the minimum 2147483647?"). For digit problems specifically, min = 9 is clearer. Use INT_MAX when the domain is unknown, and use the known bound when it's known.

5. What if the input has leading zeros like "007"?

Leading zeros aren't stored in an integer. When C reads "007" as an int, the value is 7 — one digit. The smallest digit of 7 is 7. If you need to preserve leading zeros (a common scenario for PIN codes or zip codes), store the input as a string and process characters instead of digits. That's a different program though — the "smallest digit" problem treats the input as a mathematical number, not as a fixed-width string.

6. How could I find the second smallest digit?

Same approach as finding the second largest, but flipped: track two variables min and second_min. For each digit, if it's smaller than min, shift min into second_min and set min to the new digit. Otherwise, if it's smaller than second_min but greater than or equal to min, update second_min only. Start min = 9 and second_min = 9. It's a small extension but a favourite interview question, because it catches people who only practised the single-min version.

💡 Tip: Compare this program side-by-side with assignment 7 (largest digit). The differences are just two lines — the comparison operator and the initial value. Try writing a combined program that tracks both min and max in the same loop. Once you've done that, you'll see that "running minimum" and "running maximum" are really two instances of the same abstract pattern, and switching between them is nearly mechanical.

📖 Related Tutorials

  • 6. Count the Digits in an Integer Using a While Loop
  • 7. Find the Largest Digit in an Integer Using a Do-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
  • While Loop
  • Do-while Loop
  • All 30 Loop Assignments

Previous Topic: -->> 7. Find the Largest Digit in an Integer Using a Do-While Loop   ||   Next Topic: -->> 9. Count the Occurrences of a Specific Digit Using a For 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.