Write a program that asks the user how many primes should be

Write a program that asks the user how many primes should be displayed. Then, using a combination of loops and conditionals, display the amount of prime numbers that the user specified. Remember, a prime number is a value that is divisible only by 1 and itself.

Solution

Prime.cpp

#include <iostream>

using namespace std;

int main()
{
int n,i=0,j=2;
cout << \"Enter how many primes should be displayed: \";
cin >> n;
bool flag = true;
while(i<n){
flag = true;
for (int f = 2; f <= j / 2; f++) {
   if (j % f == 0) {
   flag=false;
   }
  
   }
  
   if(flag) {   
   cout<<j<<\" \";
   i++;
   }
   j++;
}
cout<<endl;
return 0;
}

Output:

sh-4.3$ g++ -std=c++11 -o main *.cpp                                                                                                                                                                                            

sh4.3$ main                                                                                                                                                                                                                    

Enter how many primes should be displayed: 20                                                                                                                                                                                   

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

 Write a program that asks the user how many primes should be displayed. Then, using a combination of loops and conditionals, display the amount of prime number

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site