C++ Program to Display First N Prime Numbers

Prime number

C++ program to display first n prime numbers has been shown here. Here n is a positive integer. For example if n = 5, we get first 5 prime numbers i.e. 2, 3, 5, 7, 11.



Page contents:

1. Program & Output




1. C++ Program & output to display first N prime numbers

Code has been copied
/**********************
  alphabetacoder.com
C++ program to display 
first N prime numbers
***********************/

#include <iostream>
#include <cmath>

using namespace std;

// function to check prime
int check_prime(int num) {
    // declare variables
    int i;
    // 1 is not prime
    if (num == 1)
        return 0;
    // check divisibility of num
    for (i = 2; i <= sqrt(num); i++) {
        if (num % i == 0) {
            return 0; // num is composite so return false
        }
    }
    // num is prime so return true
    return 1;
}

int main() {
    // declare variables
    int n, num, count;

    // take input of the number
    cout << "Enter the no. of primes = ";
    cin >> n;

    // initialize
    num = 1;
    count = 0;

    cout << "First " << n << " primes: ";
    // find n number of primes
    while (count < n) {
        // check if current number is prime
        if (check_prime(num)) {
            cout << num << " ";
            count++; // increment counter
        }
        num++; // increment number
    }

    return 0;
}

Output


Case 1:

Enter the no. of primes = 5

First 5 primes: 2 3 5 7 11


Case 2:

Enter the no. of primes = 20

First 20 primes: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71