Checkpoint 7.9.1.
- (x % 2 == 1 && x == 7)
- 0
- (x % 2 == 0 || x + 1 == 4)
- 1
Match the conditional statement to its output, assuming it is outputted using cout and x = 3.
Try again!boolean
values, just like any other type, which is often convenient for hiding tests inside functions. If you think you might want to check the parity (evenness or oddness) of numbers often, you might want to โwrapโ this code up in a function, as follows:
#include <iostream>
using namespace std;
bool isOdd(int number) {
bool result = false;
if (number % 2 == 1) {
result = true;
} else {
result = false;
}
return result;
}
int main() {
cout << isOdd(3) << endl;
cout << isOdd(4) << endl;
cout << isOdd(15) << endl;
}
isOdd
. It is common to give boolean
functions names that sound like yes/no questions. The code itself is straightforward, although it is longer than it needs to be. There are multiple ways to write the code for that function. We could return the answer as soon as it is identified:
bool isOdd(int number) {
if (number % 2 == 1) {
return true;
} else {
return false;
}
// never get here!
}
return
, it leaves the function and returns the value. So in that version the function will never reach the line where the comment is. Returning from many places in a function can get confusing, so many programmers prefer to try to stick to one return statement at the very end. Even if we restrict ourselves to that structure, we can simplify things by recognizing there is no need to change the variable to false
if the number is not odd:
bool isOdd(int number) {
// This default value will be used if it is not changed in the if
bool result = false;
if (number % 2 == 1) {
return true;
}
return result;
}
number % 2 == 1
has a boolean value that matches what we want to return. That means we could write the function as just:
bool isOdd(int number) {
return number % 2 == 1;
}