[Solved] What is wrong with this C++ code?


first of all your

bool prime;

is not initialized. Second it should be initialized inside do while() loop and it is better to move that variable declaration there:

    bool prime = false; // move it here and initialize
    for (i = 2; i < n; ++i) {
        if (n % i == 0)
            prime = true;
    }

and you use boolean flag in reverse, which makes your program unreadable, you better fix that:

    bool prime = true; // move it here and initialize
    for (i = 2; i < n and prime; ++i) {
        if (n % i == 0) 
            prime = false;
    }
    if (prime) 
        cout << "The number is prime.";
    else
        cout << "The number is not prime.";

0

solved What is wrong with this C++ code?