Programming Examples
Java program to check number is prime or not using function
Write java Function to check number is prime or not using function
Solution
import java.util.*;
public class PrimeNumber {
public static boolean isPrime(int num)
{
boolean prime = true;
for (int i = 2; i <= num / 2; i++)
{
if (num % i == 0)
{
prime = false;
break;
}
}
return (prime);
}
public static void main(String[] args) {
int num;
char ch = 'y';
Scanner sc=new Scanner(System.in);
while (ch == 'y')
{
System.out.print("\nEnter a number :");
num = Integer.parseInt(new Scanner(System.in).nextLine());
if (isPrime(num))
{
System.out.println("\nEntered number is a prime number.");
}
else
{
System.out.println("\nEntered number is not a prime number.");
}
System.out.print("\nContinue? (y/n): ");
ch = sc.nextLine().charAt(0);
}
}
}
Output