A second form of conditional execution is alternative execution, in which there are two possibilities, and the condition determines which one gets executed. The possibilities are called branches, and the condition determines which branch gets executed. One branch is executed if the condition is true. Otherwise (else) the alternative branch is executed. This snippet uses this if/else structure to say if a number is odd or even:
if (x % 2 == 0) {
cout << "x is even";
} else {
cout << "x is odd";
}
If the remainder when x is divided by 2 is zero, then we know that x is even, and this code displays a message to that effect. If the condition is false, the second set of statements is executed. Since the condition must be true or false, exactly one of the alternatives will be executed.
// Same behavior, but redoes the work to check even/odd
if (x % 2 == 0) {
cout << "x is even";
}
if (x % 2 != 0) {
cout << "x is odd";
}
In that version, we have to write the same basic logicββdivide by two and compare the remainder to 0β-m-twice. Writing the same code twice means more work for us, more work for the computer, and more chances for a mistake.
Construct a block of code that comments on the price of a meal at a restaurant. If the price is more than $30.00, print βExpensive!β. If the price is less than $30.00, print βInexpensive!β: