AP® Computer Science A · Unit 2 · Topic 2.3

if-else and else-if Chains

An else-if chain tests its conditions in order and runs only the first branch that comes out true, skipping every condition after it. That's different from a stack of separate if statements, which tests every condition no matter what.

A grade calculator needs an else-if chain because a score should land in exactly one bucket. If you write four separate if statements, each one gets checked independently, with no memory of what the others decided. A score of 95 is ≥ 90, but it's also ≥ 80 and ≥ 70, so all three of those separate ifs would fire, printing A, B, and C. Chaining them with else if links the branches together: once one condition is true, the rest of the chain is skipped entirely.

Here's the mechanism: the chain tests its first condition. If true, it runs that branch and jumps past everything else in the chain, including the final else. If false, it moves to the next else-if condition and asks again. This repeats top to bottom until something is true, or until every condition has failed, in which case control falls into the final plain else. Order matters enormously, because the chain commits to the FIRST true condition, not the most specific one. Put loose conditions first and tighter ones become unreachable dead code.

This topic sits right next to loops in the unit for a reason: both are about control flow that a trace table can capture one decision at a time. Where a loop re-asks the same condition pass after pass, an else-if chain asks a sequence of different conditions exactly once each, then stops. Tracing a chain means walking down the list, marking each condition true or false, and noting which single branch actually executes.

Key terms

else-if chain
A sequence of linked conditions where only the first one that evaluates to true gets its branch executed.
fall through to else
When a value fails every condition in the chain and control lands in the final plain else block.
branch
One block of code attached to a single condition in an if-else-if structure.
condition order
The top-to-bottom sequence conditions are tested in, which determines which branch wins when a value satisfies more than one.

Watch it explained

  1. How it worksHow does an else-if chain stop testing the moment one of its conditions comes out true?
  2. Worked exampleTrace a grade chain for a score of 85 with cutoffs sitting at 90, 80, and 70.
  3. Worked exampleFind what an else-if chain ordered 70, then 80, then 90 prints for a score of 95.
  4. Common mistakeWhy doesn't a run of separate if statements behave like one else-if chain?

Check yourself

Your turn1 of 2
A chain has 5 'else if' conditions in a row, each testing a different range, with a final plain else at the end. If a value fails EVERY one of the conditions and falls into the final else, how many of the else-if conditions get tested along the way?

End of topic.