B2.3.2 · Programming constructs
Selection structures
By the end you can
Construct nested if-else and multi-way selection with compound Boolean operators and short-circuit evaluation.
allows a program to choose alternative paths of execution based on whether a Boolean condition evaluates to true or false.
Single, binary, and multi-way branching#
- Single-branch (if): Executes a block of instructions only when the condition is true; otherwise skips past.
- Two-branch (if - else): Chooses between exactly two mutually exclusive execution paths.
- Multi-way branching (if - else if / switch - case): Evaluates a series of conditions sequentially until the first true condition matches.
Compound Boolean conditions and short-circuiting#
Conditions can be combined using logical operators:
- AND (
&&/and): True only if both operands evaluate to true. - OR (
||/or): True if at least one operand evaluates to true. - NOT (
!/not): Inverts the truth value of the operand.
Most modern languages employ . In A AND B, if A is false, B is never tested. In A OR B, if A is true, B is never tested. Engineers use this to write safe guard clauses (e.g. if (arr != null && arr.length > 0)).
Check yourself
Selection constructs
Quick questions, made fresh every time and marked here. Do a few until they feel easy.
Exam practice
Paper 1-style questions
3 questions · 9 marks
Write your answer as you would in the exam, then show the mark points and tick each one your answer made. These are our own questions in the style of the exam, not past-paper questions.
1.Trace the output for score = 85 and isHonors = true in the given nested conditional logic.
[3]Trace: Follow the program or process step by step, recording the values.
2.Explain what short-circuit evaluation means in Boolean expressions such as (x != 0 && total / x > 5).
[2]Explain: Give reasons: say what happens AND why, or how one thing causes another.
3.Compare multi-way selection using a switch-case statement against an if-elif-else ladder in terms of syntax clarity, supported data types, and execution efficiency.
[4]Compare: Similarities and differences, about both things, point by point.
In a nutshell
- Selection branches execution into alternative paths based on Boolean conditions (if, if-else, switch).
- Compound conditions combine tests using logical AND, OR, and NOT operators.
- Short-circuit evaluation skips evaluating second operands if the first operand determines the truth value, protecting against runtime exceptions.
- Switch-case statements test a single variable for discrete equality matches, offering cleaner syntax and compiler jump-table optimizations.
