Java Program to Print Prime Numbers from 1 to N using For loop
ADVERTISEMENTS
Java program to print prime numbers from 1 to N using for loop. In this article, you will learn how to make a java program to print prime numbers from 1 to N using for loop.
Sample of Prime Numbers
2 3 5 7 .......... 103 107 109
Source Code
// Java Program to Print Prime Numbers from 1 to N using For loop
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x, i, j, f;
System.out.println ("Please enter the range for print the prime numbers::\n");
x = in.nextInt();
System.out.println ("\nThe prime numbers from 1 to " + x + " are::\n\n");
for (i = 1; i <= x; i++) {
// They are niether prime nor composite if as skip 0 and 1
if (i == 1 || i == 0) {
continue;
}
f = 1;
for (j = 2; j <= i / 2; ++j) {
if (i % j == 0) {
f = 0;
break;
}
}
// f = 1 means i is prime and f = 0 means i is not prime
if (f == 1) {
System.out.print (" " + i);
}
}
System.out.println ("\n");
}
}
Output
Please enter the range for print the prime numbers::
110
The prime numbers from 1 to 110 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 101 103 107 109