### How does this code work?

 ``123456789101112131415161718192021222324252627`` ``````#include #include using namespace std; int main() { int n; // Number to test for prime-ness int i; // Loop counter int is_prime = true; // Boolean flag... // Assume true for now. // Get a number from the keyboard. cout << "Enter a number and press ENTER: "; cin >> n; // Test for prime by checking for divisibility // by all whole numbers from 2 to sqrt(n). i = 2; while (i <= sqrt(n)) { // While i is <= sqrt(n), if (n % i == 0) // If i divides n, is_prime = false; // n is not prime. i++; // Add 1 to i. } // Print results if (is_prime) cout << "Number is prime." << endl; else cout << "Number is not prime." << endl; system("PAUSE"); return 0; }``````

Its a full working program that checks for a prime number, the code works well, but i could not understand what does this means.
if (is_prime)
cout << "Number is prime." << endl;
else
cout << "Number is not prime." << endl;

what is if(is_prime) mean.

kindly help.
This statement is equivalent to

if ( is_prime == true )

By the way the code contains a bug because 1 is not a prime number.:)
In `if (condition)` statement `condition` can evaluate to only two states - that is `true` or `false`.
In C++ `false` means 0. If it is not zero, then it is `true`. Since `is_prime` is an integer, it can hold values such as 1, -1, 3, 888, -200. Any of these values means `true`. Only 0 means `false`.

Notation
`if(condition)` is equivalent to
`if(condition == true)` or in yet other words
`if(condition != false)` or
`if(condition != 0)`
Last edited on

why doesn't it mean if(is_prime==false) coz there is no specification.

of course this program need some improvement
closed account (3TXyhbRD)
In C++, the condition for if, while, for is evaluated to "false" if it's 0 (zero) and evaluated to "true" otherwise.

A code like
 ``123`` ``````if (1){ // some code }``````

will always execute the if code block because 1 evaluates to true.

This can be useful because
 ``1234`` ``````int n = 1; if (n){ // some code }``````

has the same effect.

Lower case true (not TRUE, that's something else) and false are boolean literals. The false literal has like no choice but to evaluate to 0 (as a number) since that's C standard. On the other hand the true literal can evaluate to any non-zero number, however it usually evaluates to 1.

In other words, if you do `int n = true;` n will most likely be 1 and if you do `int n = false;` n will be be most likely 0.

If a variable is wanted to take only two values (true or false) it is best to use the bool data type since it's specially designed for that and it makes the code more readable.

 why doesn't it mean` if(is_prime==false)` coz there is no specification?
The logical value of the statement `is_prime==false` as a whole is `true` when `is_prime == 0` and `false` otherwise.