You are here

C++ program for prime numbers

C++ program for prime numbers: print first n prime numbers.

C++ programming code

  1. #include<iostream>
  2. #include<cmath>
  3.  
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8.    int n, status = 1, num = 3, count, c;
  9.  
  10.    cout << "Enter the number of prime numbers to print\n";
  11.    cin >> n;
  12.  
  13.    if ( n >= 1 )
  14.    {
  15.       cout << "First " << n <<" prime numbers are :-" << endl;
  16.       cout << 2 << endl;
  17.    }
  18.  
  19.    for ( count = 2 ; count <=n ;  )
  20.    {
  21.       for ( c = 2 ; c <= (int)sqrt(num) ; c++ )
  22.       {
  23.          if ( num%c == 0 )
  24.          {
  25.             status = 0;
  26.             break;
  27.          }
  28.       }
  29.       if ( status != 0 )
  30.       {
  31.          cout << num << endl;
  32.          count++;
  33.       }
  34.       status = 1;
  35.       num++;
  36.    }        
  37.    
  38.    return 0;
  39. }