In this tutorial, we will learn about the Duck number with examples and write a java program for duck numbers. Before that, you may go through the following topics in java.
What is a Duck Number?
A number is said to be a duck number if it is a positive integer number with zeroes in it. The digit zero (0) must not be present at the beginning of the number but can be present anywhere except the initial digit.
Example of duck number:
- 3210 is a duck number.
- 0183 is not a duck number because there is a zero present at the beginning of the number.
- 00132 is also not a dick number.
Now you have understood the Duck number, let us do a program to check duck numbers in java.
Java program to check whether a number is duck number or not
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | //Java Duck Number import java.util.Scanner; public class DuckNumberProgram { public static void main(String[] args) { // variables int num, temp; boolean flag = false; Scanner sc = new Scanner(System.in); //user input System.out.print("Enter a positive integer: "); num = sc.nextInt(); temp = num; //checking condition while (temp > 0) { if (temp % 10 == 0) flag = true; temp = temp / 10; } //checking for flag if (flag) System.out.println(num + " is a Duck Number"); else System.out.println(num + " is not a Duck Number"); } } |
Output:
//Run: 1
Enter a positive integer: 2015
2015 is a Duck Number
//Run: 2
Enter a positive integer: 00124
124 is not a Duck Number
//Run: 3
Enter a positive integer: 11245
11245 is not a Duck Number
You can create a separate Boolean function that will return true or false like the flag that is working in this program. Hope this article was helpful on Duck Number Program in Java