AP® Computer Science Principles · Big Idea 3 · Topic 3.6
Selection and IF Statements
A selection statement, like IF, tests a Boolean condition and uses the result to choose which block of code runs. True runs the block; false skips it.
A program that runs every line every time can't make decisions. Selection fixes that by putting a fork in the road: a condition that evaluates to true or false, and a block of statements that only runs when the condition is true. This is how a program reacts to different inputs instead of doing the same thing no matter what. A login check, a game over screen, a grade cutoff — all of these need the program to behave differently depending on circumstances, and IF is the tool that makes that possible.
Mechanically, the IF statement evaluates its Boolean condition first. If the condition is true, the program executes the statements inside the IF block, in order, then moves on. If the condition is false, it skips that whole block entirely and jumps straight to whatever comes after it. Nothing inside the block runs, not even partially — it's all or nothing based on that one true-or-false check. An ELSE, when present, gives the false branch something to do; without one, false just means skip and continue.
This connects directly to what comes next in the unit: loops also run on a Boolean condition, repeating a block instead of running it once. And once you're comfortable with a single fork, you'll combine conditions and nest IF statements inside each other to handle more complex decisions. Selection is also the first place where tracing a program by hand really matters — you have to track the value of a variable, check it against a condition, and predict exactly which path execution takes.
Key terms
- Selection
- A programming structure that chooses which block of statements to execute based on a condition.
- Boolean condition
- An expression that evaluates to exactly one of two values, true or false.
- IF block
- The set of statements that executes only when the IF statement's condition is true.
- ELSE
- An optional branch of an IF statement that runs only when the condition is false.
Watch it explained
- How it worksHow does a Boolean condition decide which block of statements the program executes?
- Worked exampleTrace a program that displays PASS when score is at least 60, given the input score 58.
- Going furtherWhat happens to the statements after an IF block when the condition turns out false?
- Common mistakeWhy doesn't an IF statement with no ELSE stop the rest of the program from running?
Check yourself
End of topic.