Ticker

6/recent/ticker-posts

Header Ads Widget

Java program to check for prime number

Java program to check prime number.


Introduction
In this tutorial we can make small program to check whether a number is a prime or not depending upon the user input we tell them that the number entered is prime or not.


Basically before going to the code part letters first define what is prime number.

Q) what is prime number?
Ans) Prime number is a natural number which have not more than two multiple to multiple.

Eg:- 2,3,5,7 and so on....



Now let's come on the code here are objective is to check whether user input number is prime or not.

Q) write a Java program to check prime number?

Sol.




import java.util.Scanner;
public class primeNumber{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num;
System.out.printf("enter number to check for prime number");
num=in.nextInt();
if(num%2==0)
System.out.print(num +"is prime");
else
System.out.print(num + "is not a prime number");
}
}



So above is the code to check whether a number is is prime or not , first the we declare the variable called num so that we can store the user input afterwards we put a message for user to enter a number, now we store that in num , applying logic to check prime number we put that in a a if else condition that if the logics get through do we have a message of the number is prime or the number is not Prime if logic fails.

I am sure you now clearly understand how the program works to make you more understandable let's go to the output.


Output:


enter number to check for prime number5
5is not a prime number






Post a Comment

0 Comments