AP® Computer Science Principles · Big Idea 3 · Topic 3.6
IF/ELSE and Which Branch Runs
An IF/ELSE evaluates one condition and runs exactly one of its two branches: the IF branch if the condition is true, the ELSE branch if it is false, never both.
An IF/ELSE statement tests a condition that can only be true or false. If it's true, the program runs the code inside the IF branch and skips the ELSE branch completely. If it's false, the program skips the IF branch and runs the ELSE branch instead. There's no scenario where both run, and no scenario where neither runs. This is what makes it a true fork in the road rather than two separate checks.
Picture the flow of control as a single thread moving down the program. At the IF/ELSE, that thread splits into two possible paths based on the condition, but only one path actually gets walked. Once that chosen branch finishes executing, the thread rejoins the main flow right after the ELSE block, and the program continues as normal. The two branches never both execute and never execute partially; the split and rejoin happen cleanly every single time the structure runs.
This matters most when you compare IF/ELSE to two separate IF statements. With IF/ELSE, the branches are mutually exclusive by construction, since only one condition decides everything. With two back-to-back IF statements, each condition is checked independently, so both blocks could run, neither could run, or just one could, depending on how the conditions relate. That independence is exactly why IF/ELSE is the tool for either-or choices, while separate IFs suit situations where multiple things might need to happen at once. This distinction sets up later work with chained IF/ELSE IF structures for more than two outcomes.
Key terms
- Condition
- A boolean expression inside an IF/ELSE that evaluates to true or false to decide which branch runs.
- Branch
- One of the blocks of code inside an IF/ELSE, either the IF block or the ELSE block.
- Flow of control
- The order in which a program's instructions are executed as it runs.
- Mutually exclusive
- Describes two outcomes where only one can happen at a time, never both.
Watch it explained
- How it worksWalk me through the flow of control splitting at an IF ELSE and rejoining right after it.
- Worked exampleFind the output of an IF ELSE displaying HOT above 30 and COLD otherwise, for a temperature of 30.
- Common mistakeWhy isn't an ELSE block the place to put code you want to run every single time?
- Going furtherWhat changes when two IF statements are written in a row instead of one IF ELSE?
Check yourself
End of topic.