Loop Assignment 6 — Count Digits of an Integer Using While Loop
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Count the Number of Digits in an Integer Using a While Loop

📑 On this page:
  • Why Divide by 10?
  • The Algorithm in Three Lines
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • Why n /= 10 peels off one digit at a time, and why this always terminates
  • How to handle the tricky case of zero, which would otherwise report 0 digits
  • Why negative numbers need absolute-value treatment before the loop
  • Why this loop is O(log n), not O(n) — and why that matters for large inputs
  • How the same digit-by-digit traversal powers the other assignments in this series

Why Divide by 10?

Here's the whole idea in one sentence: dividing a positive integer by 10 with integer division removes its last digit. 1234 / 10 = 123, 123 / 10 = 12, 12 / 10 = 1, 1 / 10 = 0. Every division makes the number shorter by one digit, and once the number reaches 0, there are no more digits left to count.

This is the decimal-number equivalent of asking "how many times can you cut this thing in half before it's gone?" Except we're not cutting in half — we're removing exactly one digit each time. The number of cuts equals the number of digits. For 1234, four cuts. For 999999, six cuts. For 12, two cuts. The loop counts the cuts, and the count is the digit count.

That simple observation — "divide by 10, count one, repeat" — is the foundation of almost every digit-based program in this series. Counting digits is the simplest one. Reversing a number, summing digits, finding the largest digit, checking Armstrong numbers, and printing digits in reverse all reuse the same loop skeleton, with different things happening inside the body. If you understand this one cleanly, the rest are variations.

💡 In one line: dividing an integer by 10 removes its last digit, so counting the number of divisions until the number becomes 0 gives the digit count.

Diagram showing 1234 repeatedly divided by 10 with arrows to 123, 12, 1, 0 — four divisions, so four digits

The Algorithm in Three Lines

In pseudocode, the whole thing is almost trivial:

count = 0
while n != 0:
    n = n / 10
    count = count + 1
print count
                                

Three lines, and the whole program is essentially that plus input reading and output printing. The interesting part is the edge cases, which is where most beginner solutions get it wrong.

Input Expected digit count Why this is worth checking
01Loop would report 0 — the classic off-by-one bug
71Single-digit positive — the loop runs exactly once
−71Negative single-digit — needs absolute value
12344Ordinary positive — the standard case
−12344Negative — same magnitude, same digit count
10000007Trailing zeros — the loop handles them naturally
214748364710Largest int — the loop does 10 iterations

The three cases that catch people are zero, negatives, and the boundary of int. Zero is the only case where a "natural" while loop returns the wrong answer (0 instead of 1). Negatives break the loop entirely if handled naively. And the largest int reminds you that the loop is bounded at 10 iterations — which is why this approach is fast regardless of input size.

Complete C Program

Program: count digits 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;
    }

    /* Zero is a one-digit number, but the loop would count it as 0 */
    if (n == 0) {
        printf("Number of digits = 1\n");
        return 0;
    }

    /* Digit count depends on magnitude, not sign */
    if (n < 0) n = -n;

    int count = 0;
    while (n != 0) {
        n = n / 10;
        count++;
    }

    printf("Number of digits = %d\n", count);
    return 0;
}
                                    

And here's a variant that uses do-while instead, which handles zero automatically because the body runs before the condition is tested:

Variant using do-while — 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 count = 0;
    do {
        count++;
        n = n / 10;
    } while (n != 0);

    printf("Number of digits = %d\n", count);
    return 0;
}
                                    

Notice that the second version doesn't need the explicit zero check. That's because do-while always executes the body at least once — so for n = 0, it counts one iteration and then exits. This is the kind of cleanup that comes from understanding which loop fits the problem. The assignment asks for while, so the main program uses that, but it's worth knowing the do-while version is shorter and arguably more elegant.

Program Output

Enter an integer: 1234
Number of digits = 4
                                

Try a few more. Input 0 and you should get 1. Input -98765 and you should also get 5 (the minus sign isn't a digit). Input 2147483647 (the largest int) and you should get 10. Input 7 and you should get 1. And input 1000000 — seven zeros and a one — and you should get 7.

Step-by-Step Explanation

Let's walk through 1234 and then look at the edge cases.

1. Reading input

scanf("%d", &n) reads a signed decimal integer. The check for != 1 catches the case where the user typed something that wasn't a number — no point continuing with a garbage value.

2. The zero special case

Zero is a one-digit number in decimal. But if we went straight to the loop without a check, the loop condition n != 0 would be false on entry, and count would stay at 0 — the wrong answer. There are two clean ways to fix this: an explicit early return (used in the main program), or switching to do-while (used in the variant above). Both are fine. The early return is arguably clearer because it makes the special case visible in the code rather than hidden in the loop choice.

3. Absolute value

For negatives, the sign bit is not a digit. −1234 has four digits, not five. Converting to positive with n = -n loses the sign, which is exactly what we want here. Note the small edge case: -INT_MIN overflows because INT_MIN's absolute value can't be represented as a positive int. That's a technicality most beginner programs ignore, and it's fine to ignore here — but worth knowing it exists.

4. The main loop

For 1234, the loop runs like this:

  1. n = 1234, count = 0 — condition n != 0 is true
  2. n = 1234 / 10 = 123, count = 1
  3. n = 123 / 10 = 12, count = 2
  4. n = 12 / 10 = 1, count = 3
  5. n = 1 / 10 = 0, count = 4
  6. Condition n != 0 is now false — loop exits

Final count = 4. That's the digit count.

5. Why the loop always terminates

Because n = n / 10 with integer division always produces a value strictly less than n for positive n. The sequence of n values is 1234, 123, 12, 1, 0 — strictly decreasing, always non-negative. A strictly decreasing sequence of non-negative integers must reach 0 in finitely many steps. This is the same termination argument as Euclid's algorithm, and it's worth internalising because it applies to a whole class of "shrink the input" loops.

6. Why the loop is O(log n), not O(n)

If the input is n, the loop runs approximately log₁₀(n) + 1 times — the number of decimal digits of n. For 1234, that's 4. For 1,000,000, that's 7. For 2,147,483,647 (the largest int), that's 10. So even for the biggest possible input, the loop runs 10 iterations. Compare this with a loop like for (i = 0; i < n; i++) which would run 2 billion iterations for the same input — a huge difference. This is the practical payoff of picking the right algorithm.

7. A subtle trap: while (n) vs while (n != 0)

Both work in C, because 0 is falsy and any other integer is truthy. So while (n) is equivalent to while (n != 0). Some programmers prefer the shorter form; others prefer the explicit comparison because it makes the intent clearer. For a teaching program, the explicit version is better because a beginner reading it can see immediately what the loop is waiting for. Style preference, not correctness.

🎯 Remember this: dividing by 10 with integer division removes the last digit. Count the divisions until the number is 0, and you have the digit count. Handle zero specially (or use do-while), take absolute values for negatives, and remember the loop runs in O(log n) — at most 10 iterations for any 32-bit int.

Frequently Asked Questions

1. Why does the loop divide by 10 and not by some other number?

Because we're working in base 10 — decimal. If you're counting digits in binary, divide by 2. In octal, divide by 8. In hexadecimal, divide by 16. The pattern generalises: to count digits in base b, divide by b. Division by 10 removes one decimal digit per step, so the number of steps is the number of decimal digits.

2. Why doesn't the loop count zero as a digit?

If n = 0, the loop condition n != 0 is false on entry — the body never runs, and count stays 0. But zero is a one-digit number! This is the classic off-by-one bug in digit-count programs. Fix it either with an explicit early return for the zero case (as in the main program) or by switching to do-while, which always executes at least once.

3. Why take the absolute value of negative numbers?

Because the minus sign isn't a digit. −1234 has four digits, not five. The digit count depends only on the magnitude, not the sign. Without the absolute value, n / 10 on a negative input behaves differently: −1234 / 10 in C is −123 (truncation toward zero), then −12, then −1, then 0 — the count would still come out 4 because of the way integer division truncates. But it's fragile (the behaviour depends on truncation semantics), and taking absolute value first is clearer and avoids surprises.

4. Can I count digits without a loop?

Yes, one line: snprintf(NULL, 0, "%d", n) — this prints n into a zero-length buffer, returning the number of characters it would have written. For an integer, that's exactly the digit count. It handles negatives (adds 1 for the '-' sign), zero (returns 1), and everything else. Some people consider it clever; others consider it slow and fragile. For a loop assignment, use the loop. For production code, the snprintf trick works if the return value is checked carefully for negatives.

5. How is this used in the other assignments in this series?

Every digit-based program in this series uses the same loop skeleton. Sum of digits: sum += n % 10 then n /= 10. Reverse a number: rev = rev * 10 + n % 10 then n /= 10. Largest digit: if (n % 10 > max) max = n % 10 then n /= 10. Armstrong check: sum the cube (or digit-count-power) of each digit, which uses the digit count from this program. Once you understand this loop, the others are copy-paste-and-adjust.

6. What about very large numbers that don't fit in int?

If you need more range, use long long and scanf("%lld", &n). The logic is identical — divide by 10, count — but the loop can go up to about 20 iterations instead of 10. For even larger numbers (like 1000-digit factorials), you'd need strings, because no built-in integer type is big enough. But that's well beyond the scope of a loop assignment.

💡 Tip: After this program, try the do-while variant. Then try modifying it to count digits in base 2 (divide by 2), base 8 (divide by 8), or base 16 (divide by 16). You'll see that the loop skeleton stays the same — only the divisor changes. That's the essence of a well-designed algorithm: the structure is independent of the details.

📖 Related Tutorials

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

Previous Topic: -->> 5. GCD of Three Numbers Using Nested Loops   ||   Next Topic: -->> 7. Find the Largest Digit in an Integer Using a Do-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.