AP CSP topic 3.6
Conditionals
Selection lets a program choose what to do based on a condition. In AP pseudocode, IF (condition) runs a block only when the condition is true, and ELSE gives a second block that runs when it is false. This is how a game decides whether you won, or an app decides whether a password is long enough.
Conditionals vocabulary
- Selection: Choosing which part of an algorithm to run based on a condition.
- Conditional statement: An IF or IF-ELSE statement that runs code only when a condition is met.
- Condition: A Boolean expression that decides which path the program takes.
- Block: A group of statements that run together, shown inside braces or a box.
AP-style practice questions
Try each one, then open the answer. To save your progress, take this quiz in the interactive course.
Skill: Code Analysis
temp ← 72
IF (temp > 80)
{
DISPLAY("Hot")
}
ELSE
{
DISPLAY("Nice")
}
1. What is displayed?
- (A) Hot
- (B) Nice
- (C) Hot Nice
- (D) Nothing
Show answer
(B) Nice 72 > 80 is false, so the ELSE block runs.
Skill: Algorithms and Program Development
2. A game should show "Level up!" when points reaches 100 or more, and nothing otherwise. Which code does this?
- (A) IF (points ≥ 100) { DISPLAY("Level up!") }
- (B) IF (points < 100) { DISPLAY("Level up!") }
- (C) REPEAT 100 TIMES { DISPLAY("Level up!") }
- (D) DISPLAY("Level up!")
Show answer
(A) IF (points ≥ 100) { DISPLAY("Level up!") } Selection runs the display only when the condition is true.
Skill: Code Analysis
x ← 10
IF (x MOD 3 = 1)
{
x ← x + 5
}
DISPLAY(x)
3. What is displayed?
- (A) 10
- (B) 11
- (C) 15
- (D) 1
Show answer
(C) 15 10 MOD 3 = 1, so the condition is true and x becomes 15.
Skill: Algorithms and Program Development
4. Which of the following best describes selection in an algorithm?
- (A) Repeating steps a fixed number of times
- (B) Running steps in a set order
- (C) Deciding which steps to run based on a condition
- (D) Storing many values in a list
Show answer
(C) Deciding which steps to run based on a condition Selection uses a condition to choose a path.