Java Program to Print Prime Numbers between 1 to 100

Here is a 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;

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

Recommended Posts
Java Program to Check a Number is Prime Number or Not
Java Program to Find LCM and GCD of Two Numbers
Java Program to Insert an Element in Array at Given Position
Java Program for Matrix Multiplication
Java Program to Check Perfect Number or Not
Java Program to Check Whether a Number is Palindrome or Not
Java Program to Check Whether a Number is Armstrong Number or Not
Java Program to Make a Simple Calculator using Switch Statement
C++ Program to Check Prime Number
C++ Program to Print All Prime Numbers Between 1 to N
Java Program to Calculate Volume of Sphere
All Java Programs