Loop Assignment 13 — Check All Even Digits Using For Loop
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Check Whether All Digits of an Integer Are Even Using a For Loop

📑 On this page:
  • What "All Even" Actually Means
  • The Flag-and-Break Pattern
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • Why this kind of check is fundamentally different from counting, summing, or finding a max
  • How the flag-and-break pattern works and why it's more efficient than checking every digit
  • Why zero counts as even — and why that matters for numbers like 2400
  • Why the loop can exit early as soon as one odd digit is found
  • How the same pattern generalises to "all digits odd", "all digits prime", "all digits distinct", and similar tests

What "All Even" Actually Means

A number's digits are all even when each one is divisible by 2. So for 2468, the answer is yes (2, 4, 6, 8 are all even). For 2469, the answer is no (9 is odd). For 2400, the answer is yes (2, 4, 0, 0 — 0 is even). For 10, the answer is no (1 is odd, even though 0 is even).

The logical structure here is different from the counting and summing programs. Those needed to look at every digit and combine results. This one can stop the moment it finds a single odd digit — because one exception is enough to break an "all" claim. No amount of even digits can rescue a number with a stray odd one. So the loop can short-circuit and exit early.

That early exit is not just a micro-optimisation. It changes what the loop means. Instead of asking "what happens after examining all the digits?" the program asks "does any digit violate the rule?" That's a different mental model — the loop searches for counterexamples rather than aggregating data. Once you see it this way, the "all digits odd", "all digits prime", "all digits distinct" versions are obvious extensions.

💡 In one line: "all digits even" fails the moment one digit is odd. So the loop runs until it finds an odd digit — or until it exhausts every digit and finds none.

Diagram showing 2468 as all-even digits and 2469 as having one odd digit, with the loop exiting early on the odd digit

The Flag-and-Break Pattern

The algorithm uses two things the previous digit programs didn't need: a flag, and an early exit.

  1. Initialize a flag to all_even = 1. Assume the number is all-even until proven otherwise.
  2. Loop over the digits, extracting each one with n % 10.
  3. Check the digit's parity. If it's odd (digit % 2 != 0), set all_even = 0 and break — no point examining more digits.
  4. After the loop, inspect the flag. If it's still 1, the number was all-even. If it's 0, an odd digit was found.

Compare this to "count the even digits" — that program has to look at every digit no matter what. This one can stop as soon as it finds a violation. For a number like 21, that means one iteration instead of two. For a number like 2222222221, that means nine iterations instead of ten. The savings are modest but real, and the pattern generalises.

Input All even? Iterations used Notes
2468Yes4All four digits examined, all even
2400Yes4Zeros count as even
0Yes1Single digit zero — even
2469No1Extracts 9 first (last digit), exits early
1234No1Extracts 4 first (even), then 3 (odd) → 2 iterations
9999No1Extracts 9, breaks immediately
22222Yes5Every digit examined, all even

The iteration counts in the table are worth looking at. For 2469, the loop exits after one iteration — because the last digit is 9 (odd), the earliest possible rejection. For 1234, the loop runs twice: it extracts 4 (even, continue), then 3 (odd, break). For 9999, it's one iteration again. The pattern is: the loop stops as soon as it finds the first odd digit, which could be anywhere from position 1 (rightmost) to position N (leftmost) of the digit sequence.

Complete C Program

Program: check whether all digits are even using a for loop

#include <stdio.h>

int main(void) {
    int n;

    printf("Enter an integer: ");
    if (scanf("%d", &n) != 1) {
        printf("Invalid input.\n");
        return 1;
    }

    /* Work with magnitude only */
    if (n < 0) n = -n;

    /* Preserve the original for the result message */
    int original = n;

    /* Handle zero — a single digit, which is even */
    if (n == 0) {
        printf("All digits of %d are even.\n", original);
        return 0;
    }

    /* Assume all digits are even until we find a counterexample */
    int all_even = 1;

    /* The for loop extracts digits from right to left.
       digit % 2 != 0 means odd — as soon as we see one, we can stop. */
    for (; n > 0; n /= 10) {
        int digit = n % 10;
        if (digit % 2 != 0) {
            all_even = 0;
            break;              /* one odd digit is enough */
        }
    }

    if (all_even) {
        printf("All digits of %d are even.\n", original);
    } else {
        printf("Not all digits of %d are even (at least one is odd).\n", original);
    }

    return 0;
}
                                    

And here's the same logic using a while loop, in case you prefer the more explicit form. The break still exits early:

While-loop variant (same logic)

#include <stdio.h>

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

    if (n < 0) n = -n;
    int original = n;

    if (n == 0) {
        printf("All digits of 0 are even.\n");
        return 0;
    }

    int all_even = 1;
    while (n > 0) {
        if ((n % 10) % 2 != 0) {
            all_even = 0;
            break;
        }
        n /= 10;
    }

    if (all_even)
        printf("All digits of %d are even.\n", original);
    else
        printf("Not all digits of %d are even.\n", original);

    return 0;
}
                                    

The only meaningful difference is where n /= 10 lives. In the for version, it's in the loop header, so it always runs — even when a break fires, the header still executes n /= 10? No, actually — break exits the loop immediately, skipping the update step. So the update only runs for non-breaking iterations. In the while version, the n /= 10 is inside the body, after the break check, so the same thing happens: break skips it. Both versions are logically identical.

Program Output

Enter an integer: 2468
All digits of 2468 are even.
                                

A few more to try. Input 2469 gives "Not all digits of 2469 are even (at least one is odd)." — the 9 disqualifies it. Input 2400 gives "All digits of 2400 are even." — zeros count as even. Input 0 gives "All digits of 0 are even." — the single digit is zero, which is even. Input 1 gives "Not all digits of 1 are even." Input 9999 gives "Not all digits of 9999 are even." Input −2468 gives "All digits of 2468 are even." (the minus sign isn't a digit).

Step-by-Step Explanation

Let's walk through 2469 (early exit) and 2468 (full loop) to see both paths.

1. Input and normalisation

Standard—take absolute value, save original for the result message. The original variable lets us say "2469" in the output rather than "0" (which is what n becomes after the loop).

2. The zero case

Zero is a single-digit number, and its digit is 0, which is even. So the answer is trivially "all even" — but the for loop's condition n > 0 would be false on entry, and the loop would skip. The explicit early return handles this without needing to trace why.

3. The flag

int all_even = 1; — start optimistic. Every iteration asks "is this digit odd?" If yes, flip to 0. If no, continue. After the loop, the flag holds the answer.

The alternative is to declare int all_even = 1; and use all_even = all_even && (digit % 2 == 0); inside the loop without a break. That works, but it processes every digit even after the answer is known. The flag-and-break version is faster and, more importantly, makes the intent clearer — "we stop as soon as we find a counterexample."

4. The early-exit path (input 2469)

Let's trace:

  1. n = 2469, digit = 9, 9 % 2 != 0 → all_even = 0, break
  2. Loop exits immediately — 2469's other three digits are never examined

One iteration, one answer. That's the point of the early exit — you don't need to know whether the other digits are even, because one odd digit already proves the answer is no.

5. The full-loop path (input 2468)

Let's trace:

  1. n = 2468, digit = 8, even → continue, n = 246
  2. n = 246, digit = 6, even → continue, n = 24
  3. n = 24, digit = 4, even → continue, n = 2
  4. n = 2, digit = 2, even → continue, n = 0
  5. Loop exits naturally (no break) — all_even is still 1

Four iterations. Every digit checked. The result is "yes, all even". The full loop is the slow path — it takes as many iterations as there are digits — but it's the path that gives the correct answer for all-even numbers.

6. Why zero counts as even

A number is even if n % 2 == 0. For 0: 0 % 2 == 0, so zero is even. This matters for inputs like 2400, 10000, and 0 — all of which have zeros and should be counted as all-even. It also means a number like 1024 is not all-even, because 1 is odd. But 1024 is all-even-looking-at-the-even-digits, since 0, 2, 4 are all even. That distinction — "all digits even" vs "some digits even" — is exactly why the assignment specifies the former.

7. The flag-and-break pattern in general

This pattern shows up whenever you need to check "does this property hold for all elements?" — all digits even, all characters alphabetic, all array elements positive, all files in a directory readable. In every case, the algorithm is: start optimistic, iterate, exit early on the first counterexample. After the loop, check whether the flag is still set. It's one of the most useful idioms in C, and once you've internalised it, you'll find yourself using it often.

The mirror pattern — "does this property hold for any element?" — is the same thing with the flag inverted. Start pessimistic (found = 0), loop, set the flag on the first positive case, then break. After the loop, check whether the flag is set. Two patterns, one underlying idea.

🎯 Remember this: for "all X" checks, start the flag at 1, iterate, break on the first counterexample. Zero is even, so it doesn't trigger the break. The early exit is the point of the pattern — you don't need to examine any digits after the first odd one.

Frequently Asked Questions

1. Why use a flag and break instead of just counting odd digits and comparing to zero?

Both work. The counting version (if (digit % 2 != 0) odd_count++;) needs to examine every digit — no early exit — because it doesn't know the answer until it's seen the whole number. The flag-and-break version can stop the moment it finds one odd digit. For a number that starts with an odd digit (in the extraction order, which is right-to-left), the savings is dramatic. The flag also makes the intent clearer: "is there any counterexample?" rather than "how many counterexamples are there?" — a small clarity win that adds up in larger codebases.

2. Is 0 even or odd?

0 is even, because 0 % 2 == 0. It's divisible by 2 with no remainder. This matters for numbers like 2400 or 10000 — their trailing zeros are digits, and they're even, so those numbers qualify as "all digits even" (assuming no other odd digits). It would be a common mistake to treat 0 as neither even nor odd and reject numbers containing it; the correct mathematical definition makes 0 even.

3. What about negative numbers?

The program takes the absolute value first, so −2468 becomes 2468 and gets the answer "all even". The minus sign isn't a digit and shouldn't affect the check. If you didn't take absolute value, the modulo operation on a negative number could produce negative results in C (−9 % 2 = −1), which would fail the "odd digit" check for the wrong reason. Normalising avoids that whole class of confusion.

4. What if the number is zero?

Zero's single digit is 0, which is even. So all digits of 0 are even. The program handles this with an explicit early return — the for loop wouldn't run for n = 0, so if we didn't check explicitly, the flag would stay at its initial value (1) and the program would still say "all even". It would be correct by accident, but the reasoning would be hidden. The explicit check makes it clear why zero is treated as all-even.

5. How would I check for "all digits odd" instead?

Same structure, inverted test. Change if (digit % 2 != 0) (odd) to if (digit % 2 == 0) (even). The flag all_odd starts at 1 and is cleared the moment an even digit is found. Zero is even, so a number containing a zero can never be all-odd — which is correct: 0 is not odd. Numbers like 13579 pass, 13790 fail. Everything else — the for loop, the break, the flag check after — is identical.

6. How would I check "all digits are distinct"?

That's a different algorithm — you can't just check each digit against a single predicate, because "distinct" is a property of the whole set, not of any single digit. The usual approach is to record which digits you've seen (a bool seen[10] array works nicely) and check for repeats during the extraction loop. Inside the loop: if (seen[digit]) { all_distinct = 0; break; } seen[digit] = true;. Different pattern — the flag is still there, but the "seen" tracking replaces the simple predicate test. Worth knowing as an extension, but it's a step up from the all-even check.

💡 Tip: Once this program clicks, try writing the "all odd" version without looking at the all-even version. Then try the "at least one even digit" version (which uses the mirror pattern — start at 0, set on the first even, break). Once you've done all three, you'll have internalised the two sides of the flag-and-break idiom, and any new "does any/all X?" question becomes a ten-second answer.

📖 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
  • 8. Find the Smallest Digit in an Integer Using a While Loop
  • 10. Calculate the Product of All Digits Using a While Loop
  • 12. Output Digits in Reverse Order Using a While Loop
  • C FOR Loop
  • break in Loops
  • All 30 Loop Assignments

Previous Topic: -->> 12. Output Digits in Reverse Order Using a While Loop   ||   Next Topic: -->> 14. Convert a Binary Number to Decimal 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.