How to print the prime number from a given Range- Java program for prime numbers

In the last article we have a detailed discussion about the prime numbers, its logic and finally, write a java program for prime numbers (Finding prime or not). Let’s in this article we will find how we can print the prime numbers between 1 to N numbers and M to N number (The limit is given by the user). Before jump into the code first look at the logic behind printing Prime numbers.

The very first thing we need to get from the user is the upper Limit as this program print the prime numbers between 1 to that limit.

Then we need to iterate the condition of prime numbers until it reaches the upper limit.

While looping if the prime number condition is true we need to print that number. This is the steps we need to follow to print the prime numbers between 1 to N.Let’s see the java code for printing Prime numbers from 1 to N.

In this above program, we get the input from the user and store the input as ‘n‘. The flag is a boolean variable which is used to identify whether the number passed or failed the Prime number condition for every iteration. If the prime number condition passes, we need to print the number. (Prime number)

The output of this program will be:

java program for prime numbers

Use your favourite IDE to run this Program OR Just copy this code into notepad and save the file as PrintPrimeNum.java [Class name.java]. Then run this program using CMD. [PrintPrimeNum.java and java PrimeNum].

Java program for prime numbers: [GIVEN RANGE]

By making a simple modification to above program we can able to set the limit from which we can print the range of prime number EX:we can print prime numbers from 78 to 600. If you have an idea about how to do this, Stop reading this and comment down below. Anyway, if you set the looping limit from the base limit to the last limit we can able to print the prime numbers from m to N. So, replace the limit of i=2 to i=m. The java program to print prime numbers in given range is given below: