C++ Print First n Prime Numbers
Posted by Samath
Last Updated: January 05, 2017

This program print the first n prime numbers. n can be any number from 1 to infinity. A prime number is a whole number greater than 1, whose only two whole-number factors are 1 and itself. The first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29.

#include<iostream> 
#include<cmath> 
 
using namespace std;
 
int main()
{
   int n, status = 1, num = 3, count, c;
   cout << "Enter amount: ";
   cin >> n;
 
   if ( n >= 1 )
   {
      cout << "First " << n <<" prime numbers are: " << endl;
      cout << 2 << endl;
   }
 
   for ( count = 2; count <=n ;)
   {
      for ( c = 2 ; c <= (int)sqrt(num) ; c++)
      {
         if ( num%c == 0 ) 
         {
            status = 0;
            break;
         }
      }

      if ( status != 0 )
      {
         cout << num << endl;
         count++;
      }
      status = 1;
      num++;
   }         
 
   return 0;
}