Java Program to print all prime numbers between 1 to n
In this program, You will learn how to print all prime numbers between 1 to n in java.
Some list of prime numbers is : 2, 3, 5, 7, 11
Example: How to print all prime numbers between 1 to n in java.
import java.util.Scanner;
class Main {
public static void main(String args[]) {
int n, i, j, p = 1;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number:");
n = sc.nextInt();
for (j = 2; j <= n; j++) {
p = 1;
for (i = 2; i < j; i++) {
if (j % i == 0) {
p = 0;
break;
}
}
if (p == 1){
System.out.println("Number is prime:" + j);
}
}
}
}
Output:
Enter a number:10
Number is prime:2
Number is prime:3
Number is prime:5
Number is prime:7