Daily Java Challenge #6 – Check Whether a Number is Prime (Beginner Level)

Daily Java Challenge #6 – Check Whether a Number is Prime (Beginner Level)
  • Save

Problem Statement

Write a Java program to check whether a number is a prime number or not.




📥 Input

A number like:
7




📤 Output

A message like:
7 is a prime number.
or
9 is not a prime number.




💡 What is a Prime Number?

A prime number is a number that is:

Greater than 1

Has only two factors: 1 and itself.


Examples:

✔ Prime: 2, 3, 5, 7, 11
❌ Not Prime: 1, 4, 6, 9, 12




🧾 Java Code

import java.util.Scanner;

public class PrimeCheck {
    public static void main(String[] args) {
        // Step 1: Get number from user
        Scanner scanner = new Scanner(System.in);
        System.out.print(“Enter a number: “);
        int num = scanner.nextInt();

        boolean isPrime = true;

        // Step 2: Check conditions
        if (num <= 1) {
            isPrime = false;
        } else {
            // Check from 2 to num-1
            for (int i = 2; i < num; i++) {
                if (num % i == 0) {
                    isPrime = false;
                    break;
                }
            }
        }

        // Step 3: Print result
        if (isPrime) {
            System.out.println(num + ” is a prime number.”);
        } else {
            System.out.println(num + ” is not a prime number.”);
        }
    }
}




🔍 Step-by-Step (Very Simple Explanation)

1. We ask the user to enter a number.


2. We check if the number is less than or equal to 1 → it’s not prime.


3. Then we try dividing it by numbers from 2 to (number – 1).


4. If any division gives a remainder of 0, it’s not prime.


5. If no number divides it fully, then it is prime!






📚 Example

👉 Input: 17
✅ Output: 17 is a prime number.

👉 Input: 20
❌ Output: 20 is not a prime number.

👉 Input: 1
❌ Output: 1 is not a prime number.




🎯 Tiny Bonus Challenge

Try making this program more efficient by checking up to square root of the number instead of checking till num – 1.




📝 Challenge #7 coming tomorrow!
Step-by-step Java learning made super easy 💛
Follow or bookmark to stay on track!

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *