Be careful when translating from English to C++. English allows you to take liberties that C++ does not. Common mathematical notation also allows you to write things that C++ does not allow.
x < y < z
You cannot write combinations of comparisons this way. Write x < y && y < z. |
x is 1 or 2
Do not try to write this as x == 1 || 2. Each operand of || is treated as a boolean expression. Expression x == 1 || 2 is the same as (x == 1) || (2), which treats 2 as a boolean value (which is considered to be true). To ask if x is 1 or 2, say x ==1 || x == 2. |
x is even
isPrime(n) is true
isPrime(n) is false
To ask if n is prime, just write isPrime(n). Do not write isPrime(n) == true. To test whether n is not prime, write !isPrime(n), not isPrime(n) == false. |
Shortly, we will see if-statements, which are similar to if-statements in Java. Some students get the idea that a boolean expression can only occur in a test, such as in an if-statement. But that is not true. If x is 2, then expression x > 0 has value true. Instead of
if(x > 0) { return true; } else { return false; }why not just write
return x > 0;which has the same effect. Similarly, instead of
if(x > y) { v = false; } else { v = true; }why not just write
v = !(x > y);or, better yet,
v = x <= y;
Give an expression that is equivalent to !(x == y), but that does not use the negation operator, !. Answer
Give an expression that is equivalent to !(x > y), but that does not use the negation operator, !. Answer
Give an expression that is true if x, y and z are all equal to one another. Answer
Give an expression that is equivalent to isPrime(n) == false, but that does not use any comparison operator. Answer