Learn how to write a Java program to determine if a given number is a prime number using loops and conditional logic.
Java · beginner · 25 min · 27 steps · free
for loop to iterate through a range of numbers.% for checking divisibility.break statement to exit a loop early.if-else statements to solve a logical problem.public class PrimeNumberCheck {
public static void main(String[] args) {
int num = 29;
boolean isPrime = true;
if (num <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}
}
}num is declared and initialized with the value 29. This is the number we will check.isPrime is initialized to true. We assume the number is prime until proven otherwise.num is less than or equal to 1. Prime numbers must be greater than 1. The condition 29 <= 1 is false.else block is executed.for loop is initiated to check for factors. A new variable i is initialized to 2.i <= num / 2. Here, 2 <= 29 / 2 evaluates to 2 <= 14, which is true. We enter the loop body.num is divisible by i. 29 % 2 == 0 evaluates to 1 == 0, which is false.i is now 3.3 <= 14 is true.29 % 3 == 0 evaluates to 2 == 0, which is false.i is incremented to 4. The condition 4 <= 14 is true. 29 % 4 is not 0.i is incremented to 5. The condition 5 <= 14 is true. 29 % 5 is not 0.i is incremented to 6. The condition 6 <= 14 is true. 29 % 6 is not 0.i is incremented to 7. The condition 7 <= 14 is true. 29 % 7 is not 0.i is incremented to 8. The condition 8 <= 14 is true. 29 % 8 is not 0.i is incremented to 9. The condition 9 <= 14 is true. 29 % 9 is not 0.i is incremented to 10. The condition 10 <= 14 is true. 29 % 10 is not 0.i is incremented to 11. The condition 11 <= 14 is true. 29 % 11 is not 0.i is incremented to 12. The condition 12 <= 14 is true. 29 % 12 is not 0.i is incremented to 13. The condition 13 <= 14 is true. 29 % 13 is not 0.i is incremented to 14. The condition 14 <= 14 is true. 29 % 14 is not 0.i is incremented to 15.15 <= 14 is false. The loop terminates.isPrime is true.isPrime is true, this line is executed, printing the result to the console.num instead of num / 2 or sqrt(num), which is inefficient.< instead of <=).Math.sqrt(num)).← Checking for Vowels in a String