Let’s learn java program to print prime numbers upto n.

## Java program to print prime numbers upto n

To generate prime numbers upto n we are using two for loops, one for counting numbers upto ‘n’ and other loop for validating if number is prime or not.

Last step is to check whether if number is prime or not. Here’s the program to print prime numbers upto n.

import java.util.Scanner; public class PrimeUptoN { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a, b, number, counter; System.out.println("Please enter max number till which you want to print prime number: "); number = sc.nextInt(); System.out.println("Prime numbers are: "); for(a = 2; a <= number; a++) { counter = 0; for(b = 1; b <= a; b++) { if(a % b == 0) { counter++; } } if(counter == 2) { System.out.print(a + " "); } } sc.close(); } }

**Output:**

Please enter max number till which you want to print prime number:

10

Prime numbers are:

2 3 5 7

Please enter max number till which you want to print prime number:

50

Prime numbers are:

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Also read – polymorphism in java