1 min read

AIM: – Write a program to print first n prime numbers in Java.

Prime Number:

A prime number is a whole number greater than 1 whose only factors are 1 and itself. A factor is a whole numbers that can be divided evenly into another number. The first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29. Numbers that have more than two factors are called composite numbers.

Here we are writing about Write a program to print first n prime numbers in Java. Our initiative is that user understand code by reading comment so that he/she can became capable to any understand code in this programming world.

Source Code: –

import java.util.Scanner;

public class PrintNPrime {

    public static void main(String[] args) {

        int n, num, flag, j, i=2, count = 0;
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the value of n:- ");
        n = scanner.nextInt();

        System.out.println("First " + n + " Prime numbers are:- ");

        //Count is used to keep the track the number of prime numbers printed.
        while(count < n) {
            num = i;
            flag = 0;
            
            /*Checking if a number is prime. If it is not prime then flag
            * is incremented by 1 and we come out of the loop.
            */
            for(j =2; j<=num/2; j++) {
                if(num % j == 0) {
                    flag++;
                    break;
                }
            }
            //If value of flag is 0 here, then the number is prime and it is printed.
            if(flag == 0) {
                System.out.print(num + " ");
                count++;
            }
            i++;
        }
    }
}

Output:

Categories: Uncategorized

Vishal Sharma

Currently pursuing Computer Science degree from G.B Pant Government Engineering college, New Delhi.

0 Comments

Leave a Reply