Google News
logo
Java program to display Prime Numbers from 1 to 100 and 1 to n
Here are two Java programs to display prime numbers from 1 to 100 and 1 to n :

Java program to display prime numbers from 1 to 100 :

Program :
public class PrimeNumbers {
    public static void main(String[] args) {
        int num;
        boolean isPrime;
        System.out.println("Prime numbers between 1 and 100 are: ");

        for (int i = 2; i <= 100; i++) {
            isPrime = true;
            for (int j = 2; j <= i / 2; j++) {
                if (i % j == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                System.out.print(i + " ");
            }
        }
    }
}
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 


Java program to display prime numbers from 1 to n :

 

Program :
import java.util.Scanner;

public class PrimeNumbers {
    public static void main(String[] args) {
        int num;
        boolean isPrime;
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a positive integer: ");
        num = input.nextInt();
        input.close();
        System.out.println("Prime numbers between 1 and " + num + " are: ");

        for (int i = 2; i <= num; i++) {
            isPrime = true;
            for (int j = 2; j <= i / 2; j++) {
                if (i % j == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                System.out.print(i + " ");
            }
        }
    }
}
Output :
Enter a positive integer: 50
Prime numbers between 1 and 50 are: 
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 
Both programs use a nested loop to check if a number is prime or not. The outer loop iterates from 2 to either 100 or n, while the inner loop checks if the number is divisible by any number between 2 and half of the number.

If the number is divisible, then it is not a prime number and the inner loop is exited using the break statement. If the number is not divisible by any number between 2 and half of the number, then it is a prime number and it is printed.