๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

WAP to print all prime numbers between 1 to 100 in Java  


What are Prime Numbers ?
  • A prime number is a natural number greater than 1 that has only two factors: 1 and itself.
  • Examples: 2, 3, 5, 7, 11, 13, 17, etc.
  • Non-prime numbers (composite): 4, 6, 8, 9, 10 (since they have more than two factors).
Logical Steps:
  • Iterate through numbers from 2 to 100.
  • For each number, check divisibility from 2 to the square root of the number.
  • If the number is divisible by any value in this range, it is not prime.
  • If no divisors are found, the number is prime.
  • Print all prime numbers.
Programs:
  • Below is the simple program:
    public class PrimeNumbers1to100
    {
        public static void main(String[] args)
        {
            System.out.println("Prime numbers between 1 and 100 are:");
    
            for (int num = 2; num <= 100; num++)  // Loop from 2 to 100
            {
                boolean isPrime = true;
    
                for (int i=2; i < num/2; i++)
                {
                    if (num % i == 0)
                    {
                        isPrime = false;
                        break;
                    }
                }
    
                if (isPrime)  // If no divisors found, it's prime
                {
                    System.out.print(num + " ");
                }
            }
        }
    }
    Output:
    Prime numbers between 1 and 100 are:
    2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 
Program Explanation:
  • Iteration and Variables:
    • The program iterates through numbers from 2 to 100.
    • Uses a flag variable (isPrime) to indicate if a number is prime (true initially).
  • Prime Check Logic:
    • For each number, a loop checks divisibility from 2 to num / 2.
    • If num % i == 0, set isPrime = false and exit the loop (the number is not prime).
  • Display Result:
    • If isPrime = true, print the number (it is a prime number).
  • Continue to Next Number:
    • If the number is prime, move to the next iteration in the loop.