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)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
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<i; ++d)
            if (( i%d ) == 0)
            {
                isPrime=false;
                break;
            }
        if (isPrime==true)
        {
            cout << i << " Prime" << endl;
        }
    }
    return 0;
}
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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.