C++ program to print first n prime numbers - coderforcoders

Search

Wednesday, 13 March 2019

C++ program to print first n prime numbers

#include<iostream>
using namespace std;
class prime{
public:
int i=2,j,flag,count;
void printPrime(int n)
{
cout<<"The first "<<n<<" prime numbers are\n";
for(count=0;count<n;)
{
flag=0;
for(j=2;j<=i/2;j++)
if(i%j==0)
flag=1;
if(flag==0)
{
cout<<i<<"\t";
count++;
}
i++;
}
}
};
int main()
{
int n;
prime obj1;
cout<<"Please enter how many prime numbers?\n";
cin>>n;
obj1.printPrime(n);
cout<<endl;
}

Output 1:
Please enter how many prime numbers?
5
The first 5 prime numbers are
2 3 5 7 11

Output 2:
Please enter how many prime numbers?
1
The first 5 prime numbers are
2

Output 3:
Please enter how many prime numbers?
10
The first 5 prime numbers are
2 3 5 7 11 13 17 19 23 29



No comments:

Post a Comment