Practical-8
Write a Java Program that check weather the given no is prime or not.
Introduction
This tutorial gives an explanation of how to write a Java program that will check to see weather a given number is prime or not. This program is suitable for beginner-level programmers who are familiar with the basic concepts of Java programming. The basic commands used in this program, such as the if-statement, loops, and the modulo operator, will be explained with examples.
Code
public class Main {
public static void main (String [] args) {
int n = 15;
boolean isPrime = true;
for (int i = 2; i <= n/2; i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
if (isPrime)
System.out.println(n + " is a prime number");
else
System.out.println(n + " is not a prime number");
}
}
Output
15 is not a prime number
This program starts by declaring the int variable n, and the boolean variable isPrime. Then, a for loop is used to loop from 2 to n/2, and inside the for loop, an if statement is used to check if the given number is divisible by any of the numbers between 2 and n/2 (in this case 15). If the number is divisible by any of the number between 2 and 15, then isPrime is set to false. After the for loop is finished and the program has checked if the given number is divisible by any of the numbers, the result is printed out, whether it be is a prime number or not a prime number.