Java Program to Print Prime Numbers From 1 to 100

In this post, we will learn to code the Java Program to Print Prime Numbers From 1 to 100. Let’s understand Prime Numbers and How to Check Prime Numbers in Java Programming Language.

In a previous post, we will How to check whether a number is prime or not. Today, we will print all the prime numbers from 1 to 100 using both for loop and while loop.

Now, let’s see the Java Program to print prime numbers from 1 to 100 using for loop.

Java Program to Print Prime Numbers From 1 to 100

import java.util.*;

public class Main{
    
    public static boolean isPrime(int number){
        if(number == 1) return false;
        if (number == 2) {
            return true;
        }
        else {
          int count = 0;
            //logic
          for (int div = 2; div * div <= number ; div++) {
            if (number % div == 0) {
              count++;
            }
          }
          if(count > 0){
            return false;
          }
        }
        
        return true;
    }
    
    public static void main(String[] args){
        
        for(int n=1; n<=100; n++){
            if(isPrime(n) == true){
                System.out.println(n);
            }
        }
    }
    
}

Output

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

How Does This Program Works?

In this program, we have created a for loop from 1 to 100 and checked if each number is prime or not and printed each prime number.

To understand the optimized way to check prime numbers in Java Programming Language check this, Java Program to Check Prime Number.

This is the Java Program to Print Prime Numbers From 1 to 100 using for loop.

Java Program to Print Prime Numbers From 1 to 100 using While Loop

import java.util.*;

public class Main{
    
    public static boolean isPrime(int number){
        if(number == 1) return false;
        if (number == 2) {
            return true;
        }
        else {
          int count = 0;
            //logic
          for (int div = 2; div * div <= number ; div++) {
            if (number % div == 0) {
              count++;
            }
          }
          if(count > 0){
            return false;
          }
        }
        
        return true;
    }
    
    public static void main(String[] args){
        
        int n=1;
        while(n <= 100){
            if(isPrime(n) == true){
                System.out.println(n);
            }
            n++;
        }
    }
    
}

Output

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

Conclusion

I hope after going through this post, you understand Java Program to Print Prime Numbers From 1 to 100 and learned to code a Java Program to Check Prime Number.

If you have any doubt regarding the topic, feel free to contact us in the comment section. We will be delighted to help you.

Also Read:

Leave a Comment

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