Write a menu-driven program to accept a number and check whether it is a prime number or an automorphic number. Use a switch-case statement.
(a) Prime Number: A number is said to be a prime number if it is divisible only by 1 and itself and not by any other number.
Example: 3, 5, 7, 11, 13, etc.
(b) Automorphic Number: An automorphic number is a number which is contained in the last digit(s) of its square.
Example: 25 is an automorphic number as its square is 625 and 25 is present as the last two digits.
import java.io.*;
class Menu {
int ch, n, i, c = 0, flag = 0, s;
void check() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Display menu options
System.out.println("1. Prime");
System.out.println("2. Automorphic");
System.out.println("Enter Your Choice:");
ch = Integer.parseInt(br.readLine());
// Read the number
System.out.println("Enter a Number:");
n = Integer.parseInt(br.readLine());
// Perform actions based on user choice
switch (ch) {
case 1:
// Check for prime number
c = 0; // Reset counter
for (i = 1; i <= n; i++) {
if (n % i == 0) {
c++;
}
}
if (c == 2) {
System.out.println("Prime number.");
} else {
System.out.println("Not a Prime number.");
}
break;
case 2:
// Check for automorphic number
s = n * n;
int tempN = n;
int tempS = s;
// Determine the number of digits in the original number
while (tempN > 0) {
tempN = tempN / 10;
flag++;
}
// Check if the last digits of the square match the original number
int divisor = (int) Math.pow(10, flag);
if (s % divisor == n) {
System.out.println("Automorphic number.");
} else {
System.out.println("Not an Automorphic number.");
}
break;
default:
System.out.println("Invalid Choice.");
break;
}
}
// Main method to execute the program
public static void main(String[] args) throws IOException {
Menu menu = new Menu();
menu.check();
}
}
Variable Table
| Variable | Type | Description |
|---|---|---|
ch |
int |
To store the user's menu choice. |
n |
int |
To store the number entered by the user. |
i |
int |
Loop variable used for checking prime numbers. |
c |
int |
Counter to track the number of divisors. |
flag |
int |
To store the number of digits in the original number (used for automorphic number check). |
s |
int |
To store the square of the number. |
This code provides a menu-driven approach to determine if a number is a prime or automorphic number based on user input.
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.