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

Nested Conditionals

A nested conditional is a conditional statement placed inside the branch of another one, so the program checks a second question only after the first one has already been decided.

One big test can't sort a score into five letter grades, because a single condition only splits the world into two outcomes: true or false. To get more categories you nest conditionals, tucking a new IF inside the branch of a previous one. Each level you add narrows the range of possibilities down by one more cut, the way a game of twenty questions zeroes in on an answer by ruling out half the options at each step.

Mechanically, the program runs top to bottom. It checks the outer condition first. If that's true, it enters that branch and only then looks at the next condition nested inside it, ignoring every condition written in the outer ELSE. If the outer condition is false, it jumps straight to the ELSE and never looks at what's nested inside the branch it skipped. This is why order and structure matter: once a branch is chosen, the rest of that decision tree outside it simply does not run, saving the program from checking conditions that are already irrelevant.

Nested conditionals sit naturally next to simple conditionals and loops in the course's toolkit for controlling what code runs. Where a loop repeats the same decision many times, a nested conditional refines one decision into finer categories. Reordering or restructuring the conditions changes which path a given value takes, which is why the order of checks in a grade ladder, or any nested structure, is itself part of the algorithm's design, not just a style choice.

Key terms

Nested conditional
A conditional statement placed inside the branch of another conditional statement.
Branch
One of the blocks of code that can run depending on whether a condition is true or false.
Grade ladder
A chain of nested or sequential IF/ELSE IF conditions that sorts a value into one of several ordered categories.
ELSE branch
The block of code that runs only when the preceding condition or conditions were false.

Watch it explained

  1. How it worksHow does a nested conditional narrow the possibilities down one level at a time?
  2. Worked exampleTrace a nested conditional that assigns letter grades, for the score 84.
  3. Common mistakeWhy doesn't a later condition get checked once an earlier branch has already been taken?
  4. Going furtherWhat changes about the output when you reorder the conditions in a grade ladder?

Check yourself

Your turn1 of 2
A grade ladder nests 8 IF conditions to sort scores into categories, one more category than the number of conditions checked. How many total categories can a score fall into?

End of topic.