This java program will check a number whether it is prime or not. 3, 5, 7,13 are some prime numbers are divisible by 1 and the same number.
After running the program you will be asked to provide a number to check. Later the program will check the number by the do...while loop.
First of all it will be checked if there is any remainder after divided by 2. If there is no any remainder, then it is obviously not a prime number. The loop will be stopped. But if any remainder found, then that number will be divided by the next number 3.
import java.util.Scanner; public class PrimeNumber{ public static void main(String [] args){ //declaring integer type variables int number, i=2, result=0; //message to provide a number System.out.print("Enter a number: "); //getting input from keyboard Scanner in = new Scanner(System.in); number = in.nextInt(); //do while loop to check the logic do{ if(number%i==0){ result=1; } i++; } while (i<number); //if else statement to display the result if(result==1){ System.out.println(number +" is not a prime number"); } else { System.out.println(number +" is a prime number"); } } }
No comments:
Post a Comment