Java Online Compiler
Example: Java Program to Print Prime Numbers from 1 to N using For loop
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// 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"); } }
110
Output
Clear
ADVERTISEMENTS