July 26, 2021, Learn eTutorial

1098

Here we are explaining how to write a java program to display prime numbers from 1 to n. This program will display the prime numbers between 1 to any number. So the limit of the number n, we have to read from the user.

If a number is prime, then that number can be exactly divided by only two numbers. The first number is 1 and the second number is that number itself.

Example:2 3 5 7 11 13

Using the modulo operator we can check a number is prime or not. By using a for loop, just divide the number by 1 to that number. If the remainder becomes zero then increment the counter variable. Then check the counter variable. If the counter has a value of 2 then that number is prime.

First, we have to declare the class **PrimeNum**.Then declare the variables **i,j,n**, count as integers. Create an object of the scanner class as sc and read the value of n from the user. Here we are using nested for loop. The first loop is used to count 1 to n. The second loop is used to check the number i is prime or not by counting from i to 1.if i mod j equals zero, then we will increment the counter variable by one. And repeat the inner loop. After exiting from the inner loop, we check the value of the count. If the **count =2** then we will display that number. Count 2 means, that number can be divided by 1 and that number itself.

**STEP 1**: Declare the class **PrimeNum **with a public modifier.

**STEP 2**: Open the **main()** to start the program, Java program execution starts with the main()

**STEP 3**: Declare the integer variables **i,j,n**.

**STEP 4**: Read the value of **n **from the user.

**STEP 5**: Display prime numbers from **1** to **n**. and set **i=1**.

**STEP 6**: By using a for loop check **i<=n** then do step 7.

**STEP 7**: Asign **count=0**.set **j=1**.

**STEP 8**: By using another for loop check **j>=1** then do step 9.

**STEP 9**: If **i % j==0** then increment the count by one.

**STEP 10**: Decrement **j** by one repeat step 8.

**STEP 11**: If **count=2** then display **i**.

**STEP 12**: Increment **i** by one and repeat step 6.

` ````
import java.util.Scanner;
public class PrimeNum {
public static void main(String[] args) {
int i, j, n, count;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of n ?");
n = sc.nextInt();
System.out.println("Prime numbers from 1 to " + n + " are :");
for (i = 1; i <= n; i++) {
count = 0;
for (j = i; j >= 1; j--) {
if (i % j == 0) {
count = count + 1;
}
}
if (count == 2) {
System.out.print("" + i + " ");
}
}
}
}
```

Enter the value of n ? 100 Prime numbers from 1 to 100 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