Programming Example
Java Program to Check Spy Number
Study this program carefully to understand the logic, output, and explanation in a structured way.
int[] testNumbers = {112, 123, 22, 132};
Checking Spy Numbers: 112 is NOT a Spy Number. 123 is a Spy Number! 22 is a Spy Number! 132 is a Spy Number! Press any key to continue . . .
public class SpyNumberChecker {
// Method to check if a number is a Spy Number
public static boolean isSpyNumber(int number) {
int sum = 0, product = 1, digit;
// Extract digits and calculate sum and product
while (number > 0) {
digit = number % 10; // Get the last digit
sum += digit; // Add to sum
product *= digit; // Multiply to product
number /= 10; // Remove the last digit
}
// Check if sum equals product
return sum == product;
}
public static void main(String[] args) {
// Test numbers
int[] testNumbers = {112, 123, 22, 132};
System.out.println("Checking Spy Numbers:");
for (int num : testNumbers) {
if (isSpyNumber(num)) {
System.out.println(num + " is a Spy Number!");
} else {
System.out.println(num + " is NOT a Spy Number.");
}
}
}
}
Checking Spy Numbers:
112 is NOT a Spy Number.
123 is a Spy Number!
22 is a Spy Number!
132 is a Spy Number!
Press any key to continue . . .
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.