### Prime number program up to user defined number

Last edited on
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)
 ``12345678910111213141516171819202122232425262728`` ``````#include using namespace 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
Last edited on
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!
Another thing that I like to do is split things into functions so that you can understand what code is doing what.

 ``12345678910111213141516171819202122232425262728`` ``````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) return false; return true; } int main() { int n = getValidInput(); for (int i = 2; i <= n; ++i) if ( isPrime(i) ) cout << i << " Prime" << endl; return 0; }``````
Topic archived. No new replies allowed.