AP® Computer Science Principles · Big Idea 3 · Topic 3.7

Rewriting Nested Conditionals as Boolean Expressions

When a nested IF statement only ever results in true or false, the whole nest can be rewritten as one Boolean expression using AND, OR, or NOT, instead of multiple IF branches.

A nested conditional checks one condition, and only if that passes, checks another. When the only job of that nest is to decide true or false, the nesting is just AND in disguise. An outer IF that leads to an inner IF, which returns true only when both pass, is logically identical to one line: condition A AND condition B. The program still checks both conditions, but you've erased the scaffolding and kept the logic.

The mechanism is to trace every path through the nest and ask what truth value it produces. If true only happens when A and B both happen, write A AND B. If true happens when A happens or B happens, write A OR B. A nest that returns true when a condition fails becomes NOT of that condition. Once every branch maps cleanly onto true or false, you can replace the whole structure with one expression built from AND, OR, and NOT, and a single IF with that expression as its test.

This matters for readability and for connecting conditionals to the Boolean logic used in searches, filters, and list operations elsewhere in the course. A short AND or OR expression is easier to verify than four lines of nested IF statements doing the same job. But collapsing has a limit: it only works when every branch of the nest is deciding the same true-or-false question. A nest that assigns three different grades, or returns three different strings, is choosing between outcomes, not between true and false, so there is no single Boolean expression that captures it.

Key terms

Boolean expression
A statement built from AND, OR, and NOT that evaluates to exactly true or false.
Nested conditional
An IF statement placed inside the branch of another IF statement.
AND
A Boolean operator that is true only when both conditions joined by it are true.
Independent events
Two conditions whose outcomes don't affect each other, so their combined true probability is the product of their individual probabilities.

Watch it explained

  1. How it worksHow does a conditional that returns true or false turn into one Boolean expression?
  2. Worked exampleShow me the nested IF for age over 12 and under 20 rewritten as one AND condition.
  3. Going furtherWhat changes about readability when a five level nest becomes one very long Boolean expression?
  4. Common mistakeWhy isn't every nested conditional replaceable by a single Boolean expression?

Check yourself

Your turn1 of 2
A two-level nest of IF statements checking condition A and then condition B collapses into one condition, A AND B. If A is true on 66 percent of runs and B is true on 62 percent of runs, and A and B are independent, what percent of runs does the combined AND condition evaluate to true?

End of topic.