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


CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz