Skip to main content

Section 3.5 Worked Example: Sequential If 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 there is no else branch).

You can watch this video or read through the content below it.

Given the following declarations:

int alpha = 2, beta = 1, delta = 3, eta = 0, gamma = 0;

Evaluate these statements and determine the value of all variables used.

if (alpha > beta)
   eta = alpha + 2;
if (alpha > delta)
   gamma = alpha + 5;

Subsection 3.5.1 SG1: Diagram which statements go together.

If no { } are present, then by default all if and else branches have only a single statement:

Figure 3.5.1.

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

Because there are 2 sequential if-statements, we start with the first one, and then repeat SG2 and SG3 for the other.

First we evaluate (alpha > beta):

(2 > 1) is TRUE

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

The condition is TRUE so we execute the true branch:

eta = alpha + 2

= 2 + 2

= 4

Figure 3.5.2.

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

Because there are 2 sequential if-statements, we need to repeat SG2 and SG3 for the second if-statement in the sequence.

First we evaluate (alpha > delta):

(2 > 3) is FALSE

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

The condition is FALSE and there is no else branch, so we do nothing.

Figure 3.5.3.
Hint.

Answer: alpha = 2, beta = 1, delta = 3, eta = 4, gamma = 0

Practice Pages.

You have attempted of activities on this page.