AP CSP
AP Computer Science Principles / All lessons / Big Idea 3: Algorithms and Programming
3Big Idea 3: Algorithms and Programming
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.

Picture itscore ← 85 score ≥ 70? true false DISPLAY("Pass") DISPLAY("Retry")
A flowchart for IF/ELSE. The condition is checked once, and exactly one of the two branches runs.

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?

  1. (A) Hot
  2. (B) Nice
  3. (C) Hot Nice
  4. (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?

  1. (A) IF (points ≥ 100) { DISPLAY("Level up!") }
  2. (B) IF (points < 100) { DISPLAY("Level up!") }
  3. (C) REPEAT 100 TIMES { DISPLAY("Level up!") }
  4. (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?

  1. (A) 10
  2. (B) 11
  3. (C) 15
  4. (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?

  1. (A) Repeating steps a fixed number of times
  2. (B) Running steps in a set order
  3. (C) Deciding which steps to run based on a condition
  4. (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.

Open 3.6 in the interactive course