CSPIQ · AP Computer Science Principles · Lesson 10 of 25
CSPIQ · AP Computer Science Principles

Lesson 10: Nested Conditionals & the Robot

Big Idea 3 (AAP) · Phase 3

Objectives

Warm-Up

Movie tickets: children under 10 pay $6; everyone else pays $9, except seniors 65+ who pay $7. A programmer writes:

IF (age < 10)
{
    price ← 6
}
ELSE
{
    IF (age ≥ 65)
    {
        price ← 7
    }
    ELSE
    {
        price ← 9
    }
}

Try age = 8: first condition true → price 6, inner code never touched. Age = 70: first false → into ELSE → 70 ≥ 65 true → price 7. Age = 30: false, then false → price 9. Three ages, three paths, each visiting only the tests along its route.

That's nesting: conditionals inside conditionals, where reaching an inner test requires taking a particular outer branch. Every trace error in nested code comes from forgetting that geography.


Core Concept

Nested conditionals: the geography of branches

A nested conditional places an IF (or IF/ELSE) inside a branch of another. Two consequences:

  1. Inner conditions are only evaluated if their outer branch runs. In the warm-up, age ≥ 65 is never even checked for an 8-year-old.
  2. Exactly one leaf runs. However deep the nesting, one path from the top to one innermost block executes; everything else is skipped.

Tracing discipline: at each condition, write T or F, follow that branch only, and physically cross out the branch not taken. The exam's wrong answers are exactly the values produced by wandering into crossed-out territory.

Order matters in multi-way chains

Consider grading: 90+ → A, 80+ → B, below 80 → C. This version is broken:

IF (score ≥ 80)
{
    grade ← "B"
}
ELSE
{
    IF (score ≥ 90)          ← unreachable!
    {
        grade ← "A"
    }
    ...
}

A 95 hits score ≥ 80 first → grade B. The ≥ 90 test lives inside the ELSE — reachable only when score < 80, where it can never be true. When conditions overlap, test the most specific/extreme first. The exam loves handing you a broken chain and asking "for which input does this misbehave?" — the answer is an input satisfying a later (more specific) condition that gets captured by an earlier (broader) one.

The AP robot: rules of the game

Robot questions show a grid; the robot is a triangle pointing in its facing direction. The four primitives:

Command Effect
MOVE_FORWARD() Moves one square in the facing direction
ROTATE_LEFT() Turns 90° counterclockwise in place (no movement)
ROTATE_RIGHT() Turns 90° clockwise in place (no movement)
CAN_MOVE(direction) Returns true/false: can the robot move one square that way? direction ∈ {forward, backward, left, right} — relative to the robot's current facing

Critical conventions:

Tracing a robot program

[DIAGRAM: 3×3 grid. Robot in bottom-left cell (row 1, col 1), facing right/east.
No blocked cells. Goal: gray target circle in top-right cell (row 3, col 3).]

MOVE_FORWARD()
MOVE_FORWARD()
ROTATE_LEFT()
MOVE_FORWARD()
MOVE_FORWARD()

Trace with position + facing: start (1,1) E → (1,2) E → (1,3) E → rotate: (1,3) N → (2,3) N → (3,3) N. Goal reached. Notation tip: track (row, col, facing) as a little table, updating one command at a time — it's the robot's trace table.

CAN_MOVE + nesting: the wall-follower brain

IF (CAN_MOVE(forward))
{
    MOVE_FORWARD()
}
ELSE
{
    IF (CAN_MOVE(left))
    {
        ROTATE_LEFT()
        MOVE_FORWARD()
    }
    ELSE
    {
        ROTATE_RIGHT()
    }
}

In words: go straight if possible; otherwise turn left and go if possible; otherwise just turn right (and this pass makes no move). Read robot conditionals as behavior rules — "prefer forward, then left, else pivot right" — then apply them square by square. Once loops arrive (Lesson 11), this exact block becomes a maze-walker.


Worked Examples

Example 1 (easy): One input, one path

Problem: With n ← 12, what is displayed?

IF (n > 10)
{
    IF (n MOD 2 = 0)
    {
        DISPLAY ("big even")
    }
    ELSE
    {
        DISPLAY ("big odd")
    }
}
ELSE
{
    DISPLAY ("small")
}

Solution: 12 > 10 T → enter outer IF. 12 MOD 2 = 0 T → "big even". The ELSE branches never happen — for this input they may as well not exist.

Example 2 (medium): The broken chain

Problem: Shipping: orders over $100 ship free; orders over $50 ship for $5; others $10. For which order value does this code give the WRONG cost?

IF (total > 50)
{
    cost ← 5
}
ELSE
{
    IF (total > 100)
    {
        cost ← 0
    }
    ELSE
    {
        cost ← 10
    }
}

Solution: Take total = 150: 150 > 50 T → cost 5. Should be free. The > 100 test is unreachable (it sits where total ≤ 50). Any total over $100 is wrong — charged $5 instead of $0. Fix: test > 100 first, then > 50, then else.

Interpretation: Broad condition first = specific case swallowed. When the exam asks "which input reveals the error," look above the specific test for a broader one that captures it.

Example 3 (medium): Robot orientation

Problem: A robot faces south (down the page). It executes: ROTATE_LEFT(), MOVE_FORWARD(), ROTATE_RIGHT(), MOVE_FORWARD(). Facing south at (3,2) — row 3, column 2, rows numbered upward — where does it end, facing which way?

Solution: Facing south, ROTATE_LEFT turns counterclockwise from the robot's view: south → east. MOVE_FORWARD: (3,2) → (3,3), facing east. ROTATE_RIGHT: east → south. MOVE_FORWARD: (3,3) → (2,3). Ends at (2,3), facing south.

Interpretation: Left/right are the robot's. The reliable trick: physically rotate your pencil (or your head) to face the robot's direction before every turn. Ninety seconds of feeling silly beats a lost point.

Example 4 (AP-style): Behavior-rule reading

Problem: The robot runs the wall-follower block from section (b) exactly once. The square ahead is blocked; the square to the robot's left is open. What happens?

(A) The robot moves forward (B) The robot rotates left and moves one square (C) The robot rotates right and stays (D) The robot moves left without rotating

Solution: CAN_MOVE(forward) false → ELSE → CAN_MOVE(left) true → ROTATE_LEFT, MOVE_FORWARD. (B).

Interpretation: (D) is the trap for students who think the robot can strafe. It can't — it only ever moves forward; going left requires turning left first. That's why the rotate-then-move pair is idiomatic.


Common Mistakes

  1. Evaluating inner conditions that were never reached. An inner IF exists only inside its branch. Cross out untaken branches while tracing.
  2. Broad-before-specific chains. > 50 before > 100 makes the second unreachable. Most-specific first — and when the exam shows the broken order, the misbehaving inputs are the specific ones.
  3. Robot left/right from the reader's view. It's the robot's left. Re-orient with the triangle every rotation.
  4. Thinking ROTATE moves or CAN_MOVE moves. Rotations spin in place; CAN_MOVE only asks. Only MOVE_FORWARD changes position.
  5. Losing track after two commands. Keep a (row, col, facing) log line per command. Mental tracking fails at exactly the length the exam uses.

Practice Problems

Question 1

With x ← 7, what is displayed?

IF (x > 5)
{
    IF (x > 10)
    {
        DISPLAY ("huge")
    }
    ELSE
    {
        DISPLAY ("medium")
    }
}
ELSE
{
    DISPLAY ("small")
}
Question 2
In problem 1's code, for which x would "huge" display?
Question 3
A robot faces north. After ROTATE_RIGHT() twice, it faces:
Question 4
A robot faces west. ROTATE_LEFT() makes it face:
Question 5
CAN_MOVE(right) returns true. What has happened to the robot?
Question 6
A ticket program: under 5 free; under 13 pays $4; under 65 pays $8; otherwise $6. Which ordering of conditions works in an IF / ELSE IF chain?
Question 7
Using the broken shipping code from Example 2, what cost is assigned to a $200 order?
Question 8
A robot at (2,2) facing east runs:

IF (CAN_MOVE(forward))
{
    MOVE_FORWARD()
}
ROTATE_LEFT()
MOVE_FORWARD()

The square east of (2,2) is open; all other neighbors are open too. Where does the robot end, facing which direction? (Rows number upward, columns rightward.)

Question 9

With a ← 5, b ← 5, what is displayed?

IF (a > b)
{
    DISPLAY ("first")
}
ELSE
{
    IF (a = b)
    {
        DISPLAY ("second")
    }
    ELSE
    {
        DISPLAY ("third")
    }
}
Question 10
(Select two answers.) Which statements about nested conditionals are true?
Question 11
A robot must move from (1,1) facing north to (2,2). Which sequence works?
Question 12
For the warm-up's movie-ticket code, a customer is exactly 65. What price?

Create PT Connection

Nested decisions show up in stronger PT programs the moment one condition isn't enough: if the entry is valid, then check whether it beats the record. If your procedure's selection (Lesson 9) is nested, Written Response 2(a) gets richer — you can explain not just what each condition does but why the inner one depends on the outer:

"The outer IF verifies the input is usable; only then does the inner IF compare it against the current best. Without the nesting, an invalid entry could overwrite the record."

One caution for PT design: don't nest deeper than you can explain. Two levels with clear purpose beats four levels of tangle — the rubric rewards a working algorithm you can articulate, not complexity for its own sake.


Show answer key & explanations

(g) Answer Key

1. (C). 7 > 5 T → inner: 7 > 10 F → inner ELSE → medium. (B) requires failing the outer test; (A) requires passing the inner.

2. (B). Path to "huge": outer T (x > 5) AND inner T (x > 10). Since x > 10 implies x > 5, the requirement is simply x > 10. Composite path conditions = AND of the branch conditions along the way.

3. (D). Right twice = 180°: north → east → south.

4. (A). Facing west, counterclockwise (robot's left) goes to south. Check by compass: N→W→S→E→N is the ROTATE_LEFT cycle; from W, next is S. If you said north, you rotated the page, not the robot.

5. (C). CAN_MOVE is a question, not an action. Position and facing unchanged.

6. (B). Most specific (youngest bracket) first; each later test implicitly excludes earlier ones. (A) is broadest-first — a 3-year-old hits age < 65 and pays $8. (C) buries < 5 behind < 13, so free toddlers pay $4. (D) is false — the ranges nest, i.e., overlap.

7. (D). 200 > 50 T → cost $5, wrong (should be free). This is the "swallowed specific case" in action.

8. (A). Log per command: start (2,2) E. CAN_MOVE(forward) true → MOVE_FORWARD → (2,3) E. ROTATE_LEFT → (2,3) N (rotation in place — no movement). MOVE_FORWARD → (3,3) N. Final: (3,3), facing north. (B) forgets the last move; (C) rotates the wrong way; (D) never rotates at all.

9. (B). 5 > 5 F → ELSE → 5 = 5 T → second. (D) violates one-branch-only.

10. (A) and (C). The two geography rules from section (b). (B) is the misconception this lesson exists to kill.

11. (A). Trace: (1,1) N → forward (2,1) N → rotate right → (2,1) E → forward (2,2) E ✓. (C) marches north to (3,1). (D) turns west — off the grid. (B) faces south and tries to leave the grid.

12. (A). 65 < 10 F → ELSE → 65 ≥ 65 T (inclusive!) → $7. (B) is the strict-comparison misread.

Answer letter distribution check: C, B, D, A, C, B, D, A, B, A+C, A, A — singles: A×4, B×3, C×2, D×2 + multi (A,C). Cumulative spread through L10 ≈ A 25%, B 30%, C 24%, D 20%.


Exam tip: For every robot question, before reading the code, mark on the diagram: the robot's facing (draw an arrow), and the robot's left (draw a small L on that side). Update both marks after every ROTATE. The single habit of re-drawing the facing arrow eliminates the majority of robot errors.

← All lessons
Lesson 11 ›
Score: 0/0 correct