Skip to main content

Section 7.4 Alternative Execution (if/else)

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.
Compare that version with an equivalent snippet that uses just if statements:
// 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.

Insight 7.4.1.

DRY - Don’t Repeat Yourself. The if-else statement is a more concise way to write code that has two branches that handle opposite conditions.

Checkpoint 7.4.1.

What will be printed after main is executed?
#include <iostream>
using namespace std;

void weather(int temp) {
  if (temp < 52) {
    cout << "It is cold!";
  }
  else {
    cout << "It is warm!";
  }
}

int main() {
  int degrees = 52;
  weather(degrees);
}
  • It is cold!
  • That statement would print if degrees was less than 50.
  • It is warm!
  • Correct!
  • Nothing prints.
  • One of the statements is satisfied, so something does print.
  • Error message.
  • There is nothing in the code below that would generate an error.

Checkpoint 7.4.2.

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!”:
You have attempted of activities on this page.