[JAVA]
Write a program that prompts the user for an integer and displays if the provided integer is a prime number or not. A prime number is a number that is divisible only by 1 and itself. First few prime numbers are 2,3,5,7,11,13 and so on.
[using if-statements, and if-else-statement ]
import java.util.*;//imported for scanner class
public class prime {
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);//This class is used for obtaining inputs
int n,flag=0;
System.out.println("Enter a number to be checked whether is prime or not: ");
n=sc.nextInt();
if(n==1||n==0)
System.out.println("Number neither prime nor composite");
else
{
for (int i=2;i<n;i++)
{
if(n%i==0)
{
flag=0;
break;
}
else
flag=1;
}
if(flag==1)
System.out.println("It is a prime number");
else
{
System.out.println("It is a composite number(not prime)");
}
}
}
}
Get Answers For Free
Most questions answered within 1 hours.