An IF statement runs its block of code only when its condition is true, and an IF … ELSE statement runs exactly one of its two blocks. Putting another IF inside the ELSE block handles three or more cases, and the first condition that is true decides which block runs. In AP® Computer Science Principles, you predict what selection code does by evaluating each condition for the given values and following only the block that runs.
Quick check
With x holding 8, is (x > 5) AND (x < 8) true or false?Show answerHide answer
False.
x > 5is true, butx < 8is false, andANDneeds both. The note on Boolean expressions and logical operators covers this.x holds 3. What does IF(x > 5) { DISPLAY("big") } display?Show answerHide answer
Nothing. The condition is false, so the block is skipped.
Know these already? Jump to the practice questions
What you'll be able to do
- Predict what a code segment with
IForIF … ELSEdisplays for given values. - Determine which block of a nested conditional runs.
- Explain why the order of checks in a nested conditional matters.
- Choose conditions that send every possible value to exactly one block.
Key terms
Selection
Choosing which part of a program runs, based on whether a condition is true or false.
- In plain English
- The program takes one road or another at a fork.
- Don't write
- "Selection repeats a block of code." That is iteration.
Block
The statements inside a pair of braces, run together as one unit.
- In plain English
- The code that belongs to one branch.
- Don't write
- "The statement after the closing brace is part of the
IF."
Nested conditional
A conditional statement placed inside a block of another conditional statement.
- In plain English
- An
IFthat is only checked once an earlierIFhas sent you there. - Don't write
- "Every
IFin a nested conditional is checked."
What does an IF statement do?
On the exam reference sheet: IF(condition) { … }. The condition is evaluated once. If it is true, the block runs; if it is false, the block is skipped. Either way, the program then carries on with the statement after the closing brace.
IF(score ≥ 50)
{
DISPLAY("pass")
}
DISPLAY("done")
score | Condition | Displayed |
|---|---|---|
| 70 | true | pass done |
| 30 | false | done |
DISPLAY("done") is outside the braces, so it runs for every score.
Check yourself
Show answerHide answer
pass done, because 50 ≥ 50 is true.
How does IF … ELSE choose between two blocks?
On the exam reference sheet: IF(condition) { … } ELSE { … }. When the condition is true, the first block runs; when it is false, the ELSE block runs. Exactly one of the two always runs, never both and never neither.
IF(n MOD 2 = 0)
{
DISPLAY("even")
}
ELSE
{
DISPLAY("odd")
}
With n holding 14 this displays even; with 9 it displays odd. ELSE has no condition of its own: it means "in every other case".
Key idea
IF … ELSE always runs exactly one of its two blocks.
Check yourself
Show answerHide answer
even, because 0 MOD 2 is 0.
How do nested conditionals handle more cases?
Putting an IF … ELSE inside an ELSE block gives three or more branches. The conditions are checked from the top, and the first true one wins; everything below it is skipped.
IF(score ≥ 90)
{
DISPLAY("A")
}
ELSE
{
IF(score ≥ 75)
{
DISPLAY("B")
}
ELSE
{
DISPLAY("C")
}
}
For 80, score ≥ 90 is false, so the ELSE block runs; 80 ≥ 75 is true, so B is displayed. The inner IF only runs when the score is below 90, so it does not need to test that again.
Check yourself
Show answerHide answer
B for 75, because 75 ≥ 75 is true, and C for 74.
How do you make every case run exactly once?
Write down the ranges each branch should handle, then look for two faults:
- A gap: a value no branch handles.
IF(t < 10)followed by a separateIF(t > 10)displays nothing for 10. - An overlap: a value two branches both handle. Separate
IFstatements are each checked, soIF(x > 5)andIF(x > 10)both run for 15.
IF … ELSE cannot leave a gap, because ELSE catches everything else. To check a design, test each boundary value and one value inside each range.
Check yourself
Show answerHide answer
10, because 10 < 10 and 10 > 10 are both false.
Worked example 1: Trace two IF statements
Question: What is displayed when this code segment runs?
price ← 40
member ← true
IF(member)
{
price ← price - 5
}
IF(price > 30)
{
DISPLAY("standard")
}
ELSE
{
DISPLAY("budget")
}
DISPLAY(price)
What tells you the method
A variable changes inside one block and is tested in the next, so trace the statements in order.
Step 1: Trace each statement.
Statement Condition priceDisplayed First two lines 40 IF(member)true 35 IF(price > 30)true 35 standard DISPLAY(price)35 35 WhyThe second condition uses the new value, 35, not 40.
Step 2: Join what is displayed.
Each
DISPLAYshows its value followed by a space.WhyThat puts both results on one line.
Check it
Starting from 35 instead, price becomes 30, and 30 > 30 is false, so the code would display budget 30. The boundary goes to ELSE, as > says.
Answer
standard 35
Worked example 2: Design a shipping rule
Question: An online shop charges $5 shipping on orders under $25, $2 on orders from $25 up to but not including $50, and nothing from $50. Design a code segment that stores the charge in ship and displays it. What is displayed when total is 50?
What tells you the method
Three ranges, each handled once, so use a nested IF … ELSE.
Step 1: State the input, output and ranges.
Input:
total. Output: the charge. Ranges: below 25, then 25 to below 50, then 50 and up.WhyWriting the ranges first shows where the boundaries are.
Step 2: Write the code.
IF(total < 25) { ship ← 5 } ELSE { IF(total < 50) { ship ← 2 } ELSE { ship ← 0 } } DISPLAY(ship)WhyThe inner
IFruns only whentotalis 25 or more, sototal < 50alone marks the middle range.Step 3: Trace it with
total= 50.50 < 25is false and50 < 50is false, soshipis 0.WhyAt 50, both tests fail and the final
ELSEcatches it.
Check it
Test the other boundaries: 24 gives 5, 25 gives 2 and 49 gives 2. Every value lands in exactly one branch.
Answer
0
Worked example 3: Complete the condition
Question: This code segment should display child for ages under 13, teen for ages 13 to 19, and adult for 20 and over. Which condition can replace <MISSING CONDITION>?
IF(age < 13)
{
DISPLAY("child")
}
ELSE
{
IF(<MISSING CONDITION>)
{
DISPLAY("teen")
}
ELSE
{
DISPLAY("adult")
}
}
- A)
age ≤ 20 - B)
(age > 13) AND (age < 20) - C)
age ≥ 13 - D)
age < 20
What tells you the method
A missing condition inside an ELSE: work out which values can reach it, then test each option at the boundaries 13, 19 and 20.
Step 1: Find which ages reach the inner
IF.Only ages 13 and over, because younger ages took the first branch.
WhyThe inner condition only has to split 13–19 from 20 and over.
Step 2: Test the options at 13 and 20.
A displays teen for 20. B displays adult for 13. C is true for every age that gets there, so adult never appears. D gives teen for 13 and adult for 20.
WhyWrong options usually fail at a boundary.
Check it
With D, age 19 gives teen and age 45 gives adult, as required.
Answer
D
Your turn
Question: x holds 15 and y holds 7. What is displayed when this code segment runs?
IF(x > y)
{
IF(x MOD 2 = 0)
{
DISPLAY("P")
}
ELSE
{
DISPLAY("Q")
}
}
ELSE
{
DISPLAY("R")
}
Step 1: Evaluate the outer condition.
15 > 7is true, so the outer block runs and the outerELSEis skipped: R cannot be displayed.Step 2: Your go: evaluate the inner condition and decide what is displayed.
Show the full solutionHide the solution
Step 2. 15 MOD 2 is 1, so x MOD 2 = 0 is false and the inner ELSE runs.
Answer: Q
Traps
Trap
Once one IF in a list of separate IF statements runs, the rest are skipped.
It seems right because the code looks like a list of choices. But each separate IF checks its own condition, so several can run. Only ELSE makes the choices exclusive.
x holds 20. What do IF(x > 5) { DISPLAY("a") } and then IF(x > 15) { DISPLAY("b") } display?
a b: both conditions are true, so both blocks run.
Trap
The order of the checks in a nested conditional does not matter.
It seems right because every condition still appears in the code. But the first true condition wins. If score ≥ 75 is tested before score ≥ 90, a score of 95 displays B and never reaches the A branch.
Which check must come first so that 95 displays A: score ≥ 75 or score ≥ 90?
score ≥ 90, the stricter test.
Trap
age > 18 includes people who are exactly 18.
It seems right because 18 is the number in the condition. But > excludes the value itself; age ≥ 18 includes it.
Is 18 > 18 true or false?
False.
What's examined
On the AP® Computer Science Principles exam, selection belongs to Big Idea 3: Algorithms and Programming. Multiple-choice questions ask what a code segment displays, which condition completes it, or whether two segments give the same result. IF and IF … ELSE are on the exam reference sheet. Selection is also one of the three parts, with sequencing and iteration, that the algorithm in your Create task procedure must use.
Practice questions
- Recall In
IF(c) { blockA } ELSE { blockB }, which statement is true?
- A)
blockAruns, and thenblockBruns. - B)
blockAruns whencis false. - C) Exactly one of
blockAandblockBruns. - D) If
cis false, neither block runs.
Show answer
Answer: C. A true condition runs blockA; a false one runs blockB.
Why the others are wrong:
- A treats the two blocks as a sequence.
- B reverses which block goes with a true condition.
- D describes an
IFwith noELSE.
- Apply What is displayed when this code segment runs?
n ← 7
IF(n > 10)
{
DISPLAY("high")
}
ELSE
{
DISPLAY("low")
}
DISPLAY(n)
Show answer
Answer: low 7
Marking points:
7 > 10is false, so theELSEblock displays low.DISPLAY(n)is outside both blocks, so it always runs.
- Apply What is displayed when this code segment runs?
x ← 15
IF(x > 10)
{
DISPLAY("A")
}
IF(x > 5)
{
DISPLAY("B")
}
Show answer
Answer: A B
Marking points:
- The two
IFstatements are separate, so each is checked. - Both conditions are true for 15.
- Exam-style What is displayed when this code segment runs?
a ← 6
b ← 4
IF(a > b)
{
a ← a - b
}
IF(a > b)
{
DISPLAY("first")
}
ELSE
{
IF(a = b)
{
DISPLAY("same")
}
ELSE
{
DISPLAY("second")
}
}
Show answer
Answer: second
Marking points:
6 > 4is true, soabecomes 2.2 > 4is false and2 = 4is false, so the innermostELSEruns.
- Exam-style Segment I is
IF(x ≥ 50) { DISPLAY("pass") } ELSE { DISPLAY("fail") }. Segment II is the same but usesx > 50. For which value ofxdo they display different results?
- A) 49
- B) 50
- C) 51
- D) 100
Show answer
Answer: B. For 50, 50 ≥ 50 is true but 50 > 50 is false, so I displays pass and II displays fail.
Why the others are wrong:
- A is below the boundary: both display fail.
- C is one above the boundary: both display pass.
- D is far above it: both display pass.
- Exam-style The code should display A for scores of 90 and over, B for 75 to 89, and C below 75. Give the number of the line that stops it working.
1: IF(score ≥ 90)
2: {
3: DISPLAY("A")
4: }
5: ELSE
6: {
7: IF(score > 75)
8: {
9: DISPLAY("B")
10: }
11: ELSE
12: {
13: DISPLAY("C")
14: }
15: }
Show answer
Answer: Line 7.
Marking points:
- A score of exactly 75 fails
score > 75and displays C instead of B. IF(score ≥ 75)fixes it; every other score already lands in the right branch.
- Apply For how many of the whole numbers 1 to 10 does this code display yes?
IF((n MOD 3 = 0) OR (n > 8))
{
DISPLAY("yes")
}
Show answer
Answer: 4
Marking points:
n MOD 3 = 0is true for 3, 6 and 9;n > 8is true for 9 and 10.- Together that is 3, 6, 9 and 10: 9 counts once.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
- An
IFblock runs only when its condition is true; code after the closing brace always runs. IF … ELSEruns one block, never both.- In a nested conditional the first true condition wins, so put the strictest test first.
- Separate
IFstatements are each checked and can all run. - Test every boundary value to find gaps and overlaps.