Java Program To Print All Prime Numbers From 1 to N
Chapter:
Interview Programs
Last Updated:
24-06-2017 06:56:16 UTC
Program:
/* ............... START ............... */
import java.util.Scanner;
public class JavaRrintPrimeNumbers {
// method to check number is prime or not
static boolean isPrime(int num) {
boolean flag = true;
for (int i = 2; i <= (num / 2); i++) {
if (num % i == 0) {
flag = false;
break;
}
}
return flag;
}
public static void main(String[] args) {
int n;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of N: ");
n = scanner.nextInt();
for (int loop = 2; loop <= n; loop++) {
if (isPrime(loop) == true)
System.out.print(loop + " ");
}
}
}
/* ............... END ............... */
Output
Enter the value of N: 50
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Notes:
-
In this program we will read the value of N and print the all prime numbers from 1 to N.
Tags
Program To Print All Prime Numbers From 1 to N, Java, Interview