Your problem what that you initialized isPrime at the start of main() and never reset it. That meant that every number was not prime after the first non-prime number was detected. I fixed a few other things while I was at it, (most importantly indenting)
#include <iostream>
usingnamespace std;
int main ()
{
int n=0; // Initialize to out of bounds lets you use 1 less line
while (n <= 2)
{
cout << "Please enter a number greater than 2: " ; cin >> n;
}
for (int i=2; i<=n; ++i) //up to and including n
{
bool isPrime=true; // initialize for each test number, not only once per program
for (int d=2; d<i; ++d)
if (( i%d ) == 0)
{
isPrime=false;
break;
}
if (isPrime==true)
{
cout << i << " Prime" << endl;
}
}
return 0;
}
Oh I see what you mean, no wonder only 2 and 3 came up since 4 isn't prime. This is my third program and still getting acquainted with formatting and everything. Thanks a lot for your help, Stewbond!
int getValidInput()
{
int n = 0;
while (n <= 2)
{
cout << "Please enter a number greater than 2: ";
cin >> n;
}
return n;
}
bool isPrime(int n)
{
for (int d=2; d < i; ++d)
if (i%d)
returnfalse;
returntrue;
}
int main()
{
int n = getValidInput();
for (int i = 2; i <= n; ++i)
if ( isPrime(i) )
cout << i << " Prime" << endl;
return 0;
}