AP Computer Science Principles · Study guide

Nested Conditionals

AP® Computer Science Principles · Big Idea 3 · Algorithms and Programming

Nested Conditionals

How a decision placed inside another decision works, how to trace one without getting lost, and how an IF inside each ELSE becomes a ladder of choices.

1A decision inside a decision

Nested conditional statements are conditional statements inside other conditional statements. The first question splits the program into two paths; a second question inside one of those paths splits it again. A store's discount rule is a good example: first ask whether the shopper is a member, then, inside each answer, ask whether the total is at least $50.

Figure 1. Four possible endings, and each input reaches only one. The inner question is asked only on the branch that contains it.

Each input follows one path from the top to one ending. The inner question on the other side is never asked for that input; for the program it might as well not exist.

2Tracing nested code

Here is the same tree written in the reference language. The indentation shows the nesting: each level of indent is one level deeper in the tree.

IF (member)
{
  IF (total ≥ 50)
  {
    discount ← 20
  }
  ELSE
  {
    discount ← 10
  }
}
ELSE
{
  IF (total ≥ 50)
  {
    discount ← 5
  }
  ELSE
  {
    discount ← 0
  }
}
DISPLAY(discount)

To trace it, decide the outer condition first, step into that one block only, then decide the inner condition there. Ignore the other outer block completely.

membertotalOuter branch takenInner question askedDisplayed
true30IF blocktotal ≥ 50 is false10
true50IF blocktotal ≥ 50 is true20
false30ELSE blocktotal ≥ 50 is false0
false80ELSE blocktotal ≥ 50 is true5

Every row asks at most two questions, one per level, even though the code contains three conditions. That is the shortcut nesting gives you: once the outer answer is known, half the code drops out.

3The ELSE ladder

Putting an IF inside each ELSE is how the reference language says “if this, otherwise if that, otherwise…”. The conditions are checked from the top, and the first one that is true wins; nothing below it is checked.

IF (score ≥ 90)
{
  grade ← "A"
}
ELSE
{
  IF (score ≥ 80)
  {
    grade ← "B"
  }
  ELSE
  {
    IF (score ≥ 70)
    {
      grade ← "C"
    }
    ELSE
    {
      grade ← "D"
    }
  }
}
DISPLAY(grade)
Figure 2. An IF inside each ELSE makes a ladder. For a score of 85 the second rung is the first true one, so the grade is B.
scoreFirst true rungDisplayed
95score ≥ 90A
90score ≥ 90A
85score ≥ 80B
70score ≥ 70C
69none (final ELSE)D

Order matters. Put the lowest bar first and it catches everyone above it too:

IF (score ≥ 70)
{
  grade ← "C"
}
ELSE
{
  IF (score ≥ 80)
  {
    grade ← "B"
  }
  ELSE
  {
    grade ← "D"
  }
}
DISPLAY(grade)

A score of 95 passes score ≥ 70 at the first rung, so it displays C, and the B rung can never be reached by anyone: a score of 80 or more is always caught first. In a ladder of “at least” checks, start with the highest bar.

4Ladders versus separate IFs

Three separate IF statements look similar, but they are not nested: every one of them is checked, and every true one runs.

IF (score ≥ 90)
{
  grade ← "A"
}
IF (score ≥ 80)
{
  grade ← "B"
}
IF (score ≥ 70)
{
  grade ← "C"
}
DISPLAY(grade)

For a score of 95 all three conditions are true, so grade is set to A, then B, then C, and the program displays C. To get the ladder's results with separate IFs, each condition has to pick out its own range with AND:

IF (score ≥ 90)
{
  grade ← "A"
}
IF (score ≥ 80 AND score < 90)
{
  grade ← "B"
}
IF (score ≥ 70 AND score < 80)
{
  grade ← "C"
}
IF (score < 70)
{
  grade ← "D"
}
DISPLAY(grade)

A program checked this version against the ladder for every whole-number score from 0 to 100; they agreed every time. The ladder is shorter because each ELSE already carries the “and not any rung above” part for you.

The key idea

Trace nested conditionals from the outside in: decide the outer condition, step into that block only, then decide the inner one. In an ELSE ladder the first true condition wins and everything below it is skipped.

5When the inner IF has no ELSE

An inner IF does not need an ELSE. If its condition is false and there is no ELSE, nothing happens on that path, and every variable keeps the value it already had.

fee ← 3
IF (age < 18)
{
  IF (student)
  {
    fee ← 0
  }
}
ELSE
{
  fee ← 5
}
DISPLAY(fee)
agestudentPathDisplayed
15trueouter IF, inner IF runs0
15falseouter IF, inner IF skipped3
40trueouter ELSE5

The middle row displays 3, the value fee was given before the IF. Questions about missing ELSE blocks are really asking: “what was the variable before?”

6Worked examples

Worked Example 1 Trace it

Shipping cost

What is displayed for each input: (a) weight 12, express true; (b) weight 12, express false; (c) weight 4, express true; (d) weight 10, express false?

IF (weight > 10)
{
  IF (express)
  {
    cost ← 25
  }
  ELSE
  {
    cost ← 15
  }
}
ELSE
{
  IF (express)
  {
    cost ← 12
  }
  ELSE
  {
    cost ← 6
  }
}
DISPLAY(cost)
  1. 1
    (a) and (b): 12 > 10 is true, so step into the outer IF block. Then express picks 25 or 15.
  2. 2
    (c): 4 > 10 is false, so step into the outer ELSE. express is true, so the cost is 12.
  3. 3
    (d): 10 > 10 is false (10 is not more than 10), so the outer ELSE again; express is false, so 6.
Answer: (a) 25, (b) 15, (c) 12, (d) 6.
Worked Example 2 Check the boundaries

Ice, water, or steam

What does this segment display when temp is −5, 0, 99, and 100?

IF (temp < 0)
{
  DISPLAY("ice")
}
ELSE
{
  IF (temp < 100)
  {
    DISPLAY("water")
  }
  ELSE
  {
    DISPLAY("steam")
  }
}
  1. 1
    −5 < 0 is true: the outer IF block runs and displays ice.
  2. 2
    0 < 0 is false, so step into the ELSE; 0 < 100 is true: water. 99 takes the same path.
  3. 3
    100 < 0 is false; 100 < 100 is false: steam.
Answer: ice, water, water, steam. Test the values right at each boundary; that is where off-by-one mistakes hide.
Worked Example 3 Write the code

Movie tickets

A theater charges $8 for children under 12 and $14 for everyone else on weekends (Saturday or Sunday), and $6 and $10 on weekdays. Write nested conditionals that set price.

  1. 1
    Pick the outer question: is it a weekend? Each answer then needs the same inner question about age.
  2. 2
    Write it with the outer condition first and an inner IF/ELSE in each block:
    IF (day = "Sat" OR day = "Sun")
    {
      IF (age < 12)
      {
        price ← 8
      }
      ELSE
      {
        price ← 14
      }
    }
    ELSE
    {
      IF (age < 12)
      {
        price ← 6
      }
      ELSE
      {
        price ← 10
      }
    }
    DISPLAY(price)
  3. 3
    Check one input per ending: Saturday, age 9 gives 8; Saturday, 30 gives 14; Tuesday, 9 gives 6; Tuesday, 30 gives 10.
Answer: Four endings, four prices, and one test per ending to prove each is reachable.
Worked Example 4 Spot the silent path

Nothing displayed

For which of these values of x does the segment display nothing at all: 500, 40, −3?

IF (x > 0)
{
  IF (x > 100)
  {
    DISPLAY("big")
  }
}
ELSE
{
  DISPLAY("not positive")
}
  1. 1
    500: 500 > 0 is true, and 500 > 100 is true, so it displays big.
  2. 2
    40: 40 > 0 is true, but 40 > 100 is false, and the inner IF has no ELSE. Nothing runs.
  3. 3
    −3: −3 > 0 is false, so the outer ELSE displays not positive.
Answer: Only 40. Any x from 1 to 100 takes the silent path.

7Common mistakes

Common Mistake 1 · Checking conditions on the other branch

Once the outer condition is decided, the inner IF in the other block is never evaluated. Don't trace both sides.

Common Mistake 2 · A ladder in the wrong order

With “at least” checks, the lowest bar first catches everyone. Start with the highest bar, or the later rungs can never be reached.

Common Mistake 3 · Treating separate IFs like a ladder

Separate IF statements are all checked, and later ones can overwrite earlier ones. Only ELSE stops the rest from being checked.

Common Mistake 4 · Forgetting the old value

When an inner IF without an ELSE is false, the variable is not reset or cleared. It keeps whatever it held before.

Explain a nested conditional like this

“For member = true and total = 30, the outer condition is true, so only the outer IF block runs. Inside it, 30 ≥ 50 is false, so the inner ELSE sets discount to 10. The inner condition in the outer ELSE block is never evaluated.”

Give the outer decision, then the inner decision, then the result.