1.6.1 Nested if Statements

Make Dependent Soccer Decisions

A nested if is an if inside another branch. A soccer coach checks whether Jordan is available before checking whether Jordan has taken fewer than three turns.

The second question matters only on the available path. For another worked example of nested decisions, revisit the lesson below.

Start with the Soccer Example

Read the example once before trying to explain every line. Then use the short explanations below to connect each part of the code with the soccer task.

Make Dependent Soccer Decisions
bool isAvailable = true;
int numberOfTurns = 2;
string instruction = "Wait";

if (isAvailable)
{

    if (numberOfTurns < 3)
    {
        instruction = "Take a turn";
    }
}
Understand One Part at a Time
Follow the Worked Trace

Read the table one row at a time. Check when each value is observed: a value before a statement may differ from the value after that statement runs. Cover the result column and predict an answer before checking it.

Worked soccer trace
Available Turns Checks reached Final instruction
False 2 Outer only Wait
True 2 Outer and inner Take a turn
True 3 Outer and inner Wait
Follow the Same Idea Visually

Use the diagram to follow the same soccer example in a different form. Start at the beginning and follow one execution at a time. Compare the labeled actions with the source code; do not assume every action in the picture runs.

Make Dependent Soccer Decisions in the Wildcats soccer training model.
Make Dependent Soccer Decisions
  • New
  • Changed
  • Removed
Try a Small Change
Predict Before You Run

Write your prediction and a short reason first. If you test the change, compare the observed values with that prediction. When they differ, find the first statement or decision where your explanation stops matching the code.