Skip to main content

Section 5.3 Worked Example: If-Else Statements

Subgoals for Evaluating Selection Statements.

  1. Diagram which statements go together
  2. For if statement, determine whether expression is true or false
  3. If true – follow true branch, if false – follow else branch or do nothing if no else branch

Subsection 5.3.1

You can watch this video or read through the content below it.
Given the following declarations:
int alpha = 2;
int delta = 3;
int eta = 0;
int gamma = 0;
Evaluate these statements and determine the value of all variables used.
if (alpha > delta)
    eta = alpha + 2;
else
    gamma = alpha + 5;

Subsection 5.3.2 SG1: Diagram which statements go together.

If no { } are present, then by default all if and else branches have only a single statement:
if (alpha > delta)
   eta = alpha +2;
else
   gamma = alpha + 5;

Subsection 5.3.3 SG2: For if statement, determine whether true or false

First we evaluate (alpha > delta):
(2 > 3) is FALSE

Subsection 5.3.4 SG3: If true, follow true branch. If false, follow else branch (OR do nothing if there is no else branch).

The condition is FALSE so we execute the else branch:
gamma = alpha + 5
= 2 + 5 = 7
Answer.
Answer: alpha = 2, delta = 3, eta = 0, gamma = 7

Practice Pages.

You have attempted of activities on this page.