by Dinesh Thakur Category: Control Structures

Suppose, the value entered is say 121. It is assigned to an integer variable num. Now, num is divided by all the numbers from 2 to 8 (because a number can be divided by 1 and itself) (% rehrrns remainder). If the number is divided by any number from 2 to 8, its remainder will come to be 0 and in that case the message "Number is not prime" is displayed on the screen. 121 is not divisible by 2 but is no doubt divisible by 3 which returns remainder as 0 and hence it is not a prime number.

Algorithm For Prime Number Program:

step 1: Read num

step 2: Set b=l, c=0

step 3: Repeat through step-5 while (b <= num)

step 4: If (num mod b) equals to 0 then set c = c + 1

step 5: b = b + l

step 6: If c equals to 2 then print “num is prime”

Else print “num is not prime”

step 7: Exit

Here is the Java Example for Prime Number Program:

import java.util.Scanner;

public class PrimeNumber
                public static void main(String args[])
                  int num,b,c;
                  Scanner s=new Scanner(;
                  System.out.println("Enter A Number");
                  num =s.nextInt();
                   while(b<= num)
                       System.out.println(num +" is a prime number");
                       System.out.println(num +" is not a prime number");

Prime Number Program in Java Using Scanner

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles