Hi, I am new to c++ and while I have seemed to have tackled the Prime Number program, I want to expand it to not only display the primes, but display the number of primes. I am completely confused as to how to go about it.
To wit...
Enter a number: x
There are y number of primes in x, they are:
a,b,c,d
Do you wish to continue (y/n)?
That is what I have so far (well, minus the "there are y number of primes" part. I have attempted do/while and if/else, but to no avail.
#include <iostream>
usingnamespace std;
int main()
{
int x; // input
int y; // divisor
int z; // prime
char key; // to continue or not
cout << "This program will allow you to enter a number and will display all and how many prime numbers from that number to 0." << endl << endl;
do
{
cout << "Please enter a number: ";
cin >> x;
cout << endl;
// cout << "There are " << counter << " primes in that range." << endl;
cout << "All primes in this range are:" << endl << endl;
for (z=x; z>=2; z--)
{
bool primeNo = false;
for (y=2; y<z; y++)
{
if (z % y == 0)
{
primeNo = true;
}
}
if (primeNo == false)
{
cout << z << " ";
}
}
cout << endl << endl;
cout << "Continue (y/n)? ";
cin >> key;
}
while (key == 'y'||key == 'Y');
cout << endl << endl;
system("PAUSE");
return 0;
}
Well that is very rude. I apologise that that program is not an end all be all of all creation, but I have to start someone as at one point so did you and everyone else.
Perchance you have a solution that you opted not state, or you do not have one and simply wish to make a comment on others abilities, either way, in your case silence would have been golden.
int main()
{
int x; // input
int y; // divisor
int z; // prime
int counter;
char key; // to continue or not
cout << "This program will allow you to enter a number and will display all and how many prime numbers from that number to 0." << endl << endl;
do
{
counter=0;
cout << "Please enter a number: ";
cin >> x;
cout << endl;
//
cout << "All primes in this range are:" << endl << endl;
for (z=x; z>=2; z--)
{
bool primeNo = false;
for (y=2; y<z; y++)
{
if (z % y == 0)
{
primeNo = true;
}
}
if (primeNo == false)
{
cout << z << " ";
counter++; // <-------- increase the counter
}
}
cout << "\nThere are " << counter << " primes in that range." << endl; // print the number of primes
cout << endl << endl;
cout << "Continue (y/n)? ";
cin >> key;
}
while (key == 'y'||key == 'Y');
cout << endl << endl;
system("PAUSE");
return 0;
}