Java Program to Print Prime Numbers between 1 to 100

  • Java program to print all prime numbers between 1 to 100 using for loop.

In this java program, we have to print all prime numbers between 1 to 100. There are various methods of primality testing but here we will use a basic method of repetitive division.

A Prime number is a whole number greater than 1 that is only divisible by either 1 or itself. All numbers other than prime numbers are known as composite numbers. Composite numbers will have factors other than 1 or itself. There are infinitely many prime numbers, here is the list of first few prime numbers
2 3 5 7 11 13 17 19 23 29....

NOTE: Any prime number greater than 3 can be expressed in the form of 6N+1 or 6N-1 for some value of N.
Algorithm to check prime number or not
Let, N be a positive number.
  • For every number i, between 2 to N/2(2<= i <= N/2) check whether i divides N completely(check If i is a factor of N).
  • if (N % i == 0), then N cannot be a Prime number.
  • If none of the number between 2 to N/2 divides N completely then N is a prime number.

Java program to print all prime numbers between 1 to 100

In this java program, we iterate from 2 to 100 and for every number "i" we check whether "i" is prime number or not. If it is prime number then we print it on screen otherwise continue.

package com.tcc.java.programs;

import java.util.Scanner;

/**
 * Java Program to print all prime numbers between 1 to 100
 */
public class PrintPrimeNumbers {

    public static void main(String[] args) {
        int i, j, isPrime, n;
        System.out.println("All Prime Numbers Between 1 to 100");

        // For every number between 2 to 100, check
        //  whether it is prime number or not
        for (i = 2; i <= 100; i++) {
            isPrime = 0;
            // Check whether i is prime or not
            for (j = 2; j <= i / 2; j++) {
                // If any number between 2 to i/2 divides i
                // completely then i cannot be prime number
                if (i % j == 0) {
                    isPrime = 1;
                    break;
                }
            }

            if (isPrime == 0)
                System.out.print(i + " ");
        }

    }
}
Output
All Prime Numbers Between 1 to 100
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