Display prime number

Program to display prime numbers

Java program to display prime number

Today’s we learn about the prime numbers, A prime number is a natural number greater than 1 which are divisible by only 1 and itself. For example 2, 3, 5, 7, 11…  are prime numbers because they can neither be divided nor is a result of the multiplication.
To understand this program you should have the knowledge of for loop, if-else statements and break statement.

import java.util.Scanner;
class PrimeCheck
{
   public static void main(String args[])
   {		
    int temp;
    boolean isPrime=true;
    Scanner scan= new Scanner(System.in);
    System.out.println("Enter any number:");
    //capture the input in an integer
    int num=scan.nextInt();
        scan.close();
    for(int i=2;i<=num/2;i++)
    {
           temp=num%i;
       if(temp==0)
       {
          isPrime=false;
          break;
       }
    }
    //If isPrime is true then the number is prime else not
    if(isPrime)
       System.out.println(num + " is a Prime Number");
    else
       System.out.println(num + " is not a Prime Number");
   }
}

Program Output:

Enter any number:
19
19 is a Prime Number

Enter any number:
6
6 is not a Prime Number

I hope this post helps you to understand Prime numbers and its implementation in Java programming language.

Keep coding 🙂

2 thoughts on “Display prime number”

Leave a Reply

Your email address will not be published. Required fields are marked *