1. Write a menu driven program to accept a number and check and display whether it is a prime number or not OR an automorphic number or not. ( Use switch-case statement) a). Prime number : Prime numbers are those numbers which are only divisible by 1& by itself and not by any other number. Example : 3, 5, 7, 11, 13, 17, 19, … etc. b). Automorphic number : An automorphic number is the 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.
Answers
The programme can be written as follows.
import java.io.*; public class MenuPrimeAutomorphicNumber { public static void main(String args[])throws IOException { int i,ch,a,no,m,f=1,c=0,p; InputStreamReader in=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(in); System.out.println("1. For Prime number"); System.out.println("2. For Automorphic number"); System.out.print("Enter your choice:"); ch=Integer.parseInt(br.readLine()); switch(ch) { case 1: System.out.print("Enter number to check prime:"); no=Integer.parseInt(br.readLine()); for(i=2;i<no;i++) { if(no%i==0) { f=0; break; } } if(f==1) System.out.print("Prime number"); else System.out.print("Not Prime number"); break; case 2: System.out.print("Enter number to check Automorphic:"); no=Integer.parseInt(br.readLine()); m=no; while(m!=0) { m/=10; c++; } p=(int)Math.pow(10,c-1); a=no%p; if(no==a*a) System.out.println("Automorphic number");else System.out.println("Not Automorphic number"); break; default: System.out.println("Wrong choice"); } }} Output: 1. For Prime number 2. For Automorphic number Enter your choice:1 Enter number to check prime:5 Prime number 1. For Prime number 2. For Automorphic number Enter your choice:2 Enter number to check Automorphic: 25 Automorphic number
Answer:
Your answer is here...
Explanation:
Here using switch case (menu driven) we are going to write the following program.
import java.io.*;
public class MenuPrimeAutomorphicNumber
{
public static void main(String args[])
{
int i,ch,a,no,m,f=1,c=0,p;
Scanner scnr=new Scanner (System.in);
System.out.println("1. For Prime number");
System.out.println("2. For Automorphic number");
System.out.print("Enter your choice:");
ch=scnr.nextInt();
switch(ch)
{
case 1:
System.out.print("Enter number to check prime:");
no=Integer.parseInt(br.readLine());
for(i=2;i<no;i++)
{
if(no%i==0)
{
f=0;
break;
}
}
if(f==1)
System.out.print("Prime number");
else
System.out.print("Not Prime number");
break;
case 2:
System.out.print("Enter number to check Automorphic:");
no=Integer.parseInt(br.readLine());
m=no*no;
while(m!=0)
{
m/=10;
c++;
}
p=(int)Math.pow(10,c-1);
a=no%p;
if(no==a)
System.out.println("Automorphic number");
else
System.out.println("Not Automorphic number");
break;
default:
System.out.println("Wrong choice");
}
}
}