Java Program to display first 100 prime numbers using for loop

Here we are explaining how to write a java program to display the first 100 prime numbers. This program will display the prime numbers between 1 to 100.

What is a prime number?

Prime numbers are numbers that are greater than one and that number has only two factors. The first factor is 1 and the second factor is that number itself.

Example:3 5 7 11 13 etc..

How to implement the java program to display prime numbers from 1 to 100?

First, we have to declare the class PNum.Then declare the variables i,j count as an integer. Here we are using nested for loop. The first loop is used to count 1 to 100. The second loop is used to check the number i is prime or not by counting from i to 1.if i mod j equals zero, then we will increment the counter variable by one. And repeat the inner loop. After exiting from the inner loop, we check the value of the count. If the count =2 then we will display that number. Count 2 means, that number can be divided by 1 and that number itself.

ALGORITHM

STEP 1: Declare the class PNum with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Declare the integer variables i,j,n.

STEP 4: Display the "The First 100 prime numbers are".

STEP 5: set i=1.

STEP 6: By using a for loop check i <= 100 then do step 7.

STEP 7: Asign count=0.set j=1.

STEP 8: By using another for loop check j >= 1 then do step 9.

STEP 9: If i % j==0 then increment the count by one.

STEP 10: Decrement j by one repeat step 8.

STEP 11: If count=2 then display i.

STEP 12: Increment i by one and repeat step 6.

Java Source Code

                                          import java.util.Scanner;
public class PNum {
    public static void main(String[] args) {
        int i, j;

        System.out.println("First 100 prime numbers are :");
        for (i = 1; i <= 100; i++) {
            int count = 0;
            for (j = i; j >= 1; j--) {
                if (i % j == 0) {
                    count = count + 1;
                }
            }
            if (count == 2) {

                System.out.print("" + i + " ");
            }
        }

    }
}
                                      

OUTPUT

First 100 prime numbers 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