Duck Number in C, C++, Java & Python – Code with Explanation & Examples in Short and Simple

   

C Program

#include <stdio.h>
int main() {
    long num;
    printf("Enter a number: ");
    scanf("%ld", &num);
    long temp = num;
    int flag = 0;
    while (temp > 0) {
        if (temp % 10 == 0) { flag = 1; break; }
        temp /= 10;
    }
    if (flag && num % 10 != num) 
        printf("%ld is a Duck Number", num);
    else 
        printf("%ld is Not a Duck Number", num);
    return 0;
}

C Output

Input:
5071

Output:
5071 is a Duck Number


C++ Program

#include <iostream>
using namespace std;
int main() {
    long num;
    cout << "Enter a number: ";
    cin >> num;
    long temp = num;
    bool duck = false;
    while (temp > 0) {
        if (temp % 10 == 0) { duck = true; break; }
        temp /= 10;
    }
    if (duck && num % 10 != num)
        cout << num << " is a Duck Number";
    else
        cout << num << " is Not a Duck Number";
}

C++ Output

Input:
9023

Output:
9023 is a Duck Number


JAVA Program

import java.util.*;
class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        long num = sc.nextLong();
        long temp = num;
        boolean duck = false;
        while (temp > 0) {
            if (temp % 10 == 0) { duck = true; break; }
            temp /= 10;
        }
        if (duck && num % 10 != num)
            System.out.println(num + " is a Duck Number");
        else
            System.out.println(num + " is Not a Duck Number");
    }
}

JAVA Output

Input:
1065

Output:
1065 is a Duck Number


Python Program

num = int(input("Enter a number: "))
temp = num
duck = False
while temp > 0:
    if temp % 10 == 0:
        duck = True
        break
    temp //= 10
if duck and num % 10 != num:
    print(f"{num} is a Duck Number")
else:
    print(f"{num} is Not a Duck Number")

Python Output

Input:
704

Output:
704 is a Duck Number


In-Depth Learning – Entire Concept in Paragraphs

Example

Consider the input 1023. The first character is 1, so the number does not start with zero, and the remaining digits contain a 0. Therefore, 1023 is a Duck Number. By contrast, 0123 starts with 0, which disqualifies it even though it has zeros; leading zero means it is not a Duck Number. Another instructive case is 0 itself: it begins with zero and has no non-leading digits, so it is not a Duck Number by the common definition used in programming problems.

Real-Life Analogy

Imagine a queue for a movie hall where VIP entry rules say the first person in line cannot be wearing a hat, but anyone after the first may wear one. Think of the hat as the digit 0. If the first person is wearing a hat (the number starts with zero), the show is denied for the whole group. If someone in the middle or near the end wears a hat, that’s perfectly fine and the group qualifies. A Duck Number is the group that qualifies because the hat appears only after the first person.

What Exactly Are We Checking?

The definition boils down to two conditions that must both be satisfied. First, the first significant character (ignoring a leading + or -) must not be 0. Second, at least one 0 must appear somewhere after that first significant digit. The first condition prevents numbers like 0123 from passing; the second condition ensures that numbers such as 1234 do not qualify because they contain no zero at all. These two conditions together are both necessary and sufficient, meaning if both are true the number is a Duck Number, and if either fails it is not.

Why the String Approach Is Correct (and Safer)

When you read a number as an integer, the input mechanism typically drops leading zeros. For instance, typing 0123 and reading as an int gives 123, and you lose the very information that decides Duck-ness. That’s why robust solutions read the input as a string and examine characters directly. This also lets us support optional signs like +102 or -102. In numeric-only approaches, checking for internal zeros is easy via % 10 and / 10, but you simply cannot know if there was a leading 0 before parsing. Therefore, if your problem statement mentions “should not start with zero,” the string method is the correct, minimal, and production-safe solution.

Learning Insights

This exercise trains several foundational skills at once. You learn to parse raw input reliably by choosing a representation (string vs integer) that preserves the semantics you care about, a mindset that’s crucial in real software where format nuances matter. You also practice scanning sequences, short-circuiting once the answer is known, and dealing with signs and edge inputs. From a complexity standpoint the algorithm is linear in the number of characters, which is optimal because you must at least look at the characters to decide. It reinforces the idea that a problem’s definition should drive your data representation; if the definition talks about the “first digit,” you should work with text to ensure that digit truly is the first character provided by the user.

Common Edge Cases and How This Code Handles Them

Inputs with a sign such as +102 and -204 are accepted by skipping the sign and applying the same rule, so both are Duck Numbers because the first digit isn’t zero and there is a zero later. A single 0 is not a Duck Number because it begins with zero. A string like 0007 is not a Duck Number due to leading zeros; the first significant character is 0. Numbers like 1000, 101, and 7004 are Duck Numbers because zero appears after the first digit. Pure nonzero sequences like 123456789 are not Duck. Extremely long numeric strings still work because the logic is O(n) and uses O(1) extra space.

Proof of Correctness in Plain Words

Suppose the program prints “Duck Number.” That can only happen if the first significant digit is not 0 and there exists a 0 after it. This matches the definition exactly, so all numbers we accept are valid Duck Numbers (soundness). Conversely, if a string represents a valid Duck Number by definition, then its first significant digit is nonzero and there is at least one later zero; our scan will discover that zero and accept it, so we accept all valid Duck Numbers (completeness). Because both directions hold, the algorithm is correct.

Performance and Complexity

The algorithm scans the string at most once beyond the first significant character, leading to time complexity O(n) where n is the length of the input string, and space complexity O(1) since it uses only a few scalar variables. This is optimal; any method must inspect the characters at least once to decide.

Practical Uses of the Technique

While “Duck Number” itself is a learning construct, the technique shows up everywhere. Input validation routines often must preserve leading zeros for things like account numbers, phone numbers, SKUs, and ZIP codes, where leading zeros are meaningful. Parsing as text avoids accidental data corruption. The pattern of “inspect the first character for a special rule, then scan the rest for a property” appears in validating file formats, URLs, tokens, and protocol messages. The early-exit style you see here is also a micro-optimization used in search scans and streaming parsers.

Interview Relevance and Extensions

Interviewers appreciate this problem because it reveals whether you anchor your solution to the problem definition rather than defaulting to integer math. A common extension is a regex one-liner: for example, in many languages you can check something like ^[+-]?[1-9]\d*0\d*$ to express the rule declaratively. Another extension generalizes to other bases: a “base-b Duck Number” could be defined as having at least one zero digit not at the beginning, and the same string-based reasoning still applies. You may also be asked to count how many Duck Numbers appear in a range, which turns this into a combinatorics or digit-DP challenge if the range is huge.

Real-World Analogy, Revisited

Think of an airline boarding pass where the first character must be an alphabet letter, but somewhere later there must be a 0 as part of an internal checksum pattern. If the first character is 0, the pass is rejected. If there is no 0 later, it’s also rejected. Only passes that start correctly and have the required 0 later are accepted. Your program is that gate scanner.

Mistakes to Avoid

The most common mistake is reading as an integer and trying to detect leading zeros; you can’t, because they’re already gone. Another is accepting 0 or 000 as Duck Numbers; by the standard definition used in programming challenges they are not. A subtler mistake is missing signed inputs; always decide upfront whether to accept + or -. Finally, avoid scanning the entire string if you’ve already found a zero; break early to keep the code lean.

Testing Strategy

A solid mental test set includes 1023 (Duck), 0123 (Not Duck), 0 (Not Duck), 1000 (Duck), 1234 (Not Duck), +708 (Duck), -9001 (Duck), 0007 (Not Duck), and a long number with no zeros to exercise the full scan. If all of these pass, your logic is robust.

SEO-friendly wrap-up

This guide shows how to check a Duck Number in C, C++, Java, and Python using a safe string method that correctly handles leading zeros and optional signs. You learned the precise definition, edge cases, proof of correctness, complexity, and practical parsing lessons that apply to real projects. If you’re preparing for coding interviews or building input validators, this clear and efficient approach to detecting zeros after the first digit will help you write reliable code. Beginners searching for “duck number program in C C++ Java Python,” “how to check duck number with and without leading zero,” or “string vs numeric input validation example” will find this solution complete, accurate, and production-ready.