AP Computer Science Principles · Unit 3: Algorithms & Programming
3.6 Conditionals
Conditionals control the flow
A conditional statement lets a program execute different code depending on whether a Boolean condition is true or false. Selection using IF, ELSE, and ELSE IF blocks changes the order in which statements run, allowing programs to make decisions rather than always executing the same sequence.
IF, ELSE, and ELSE IF
An IF statement runs code only when its condition is true. Adding ELSE provides a default block that runs when the condition is false. ELSE IF lets you chain multiple conditions, checking them in order until one is true — only the first matching block executes.
Nested conditionals
A nested conditional places one IF statement inside another, allowing more complex decision-making. This lets a program check a condition only after another condition has already been satisfied, which can sometimes replace a compound Boolean expression but may increase complexity.
Key terms
- Conditional statement
- A statement that executes different code depending on whether a Boolean condition is true or false.
- Selection
- The use of conditionals (IF, ELSE, ELSE IF) to change the order in which statements execute.
- IF statement
- Runs a block of code only when its condition evaluates to true.
- ELSE IF
- Checks an additional condition when the previous IF (or ELSE IF) condition was false.
- Nested conditional
- An IF statement placed inside another IF statement, enabling more complex decision-making.
Try an AP-style question
Code
x ← 12
IF (x > 10)
{
x ← x − 5
}
ELSE
{
x ← x + 5
}
DISPLAY(x)What is displayed?
- 17
- 12
- 7
- 5
Show the answer
C. 12 > 10.
Practice 8 AP-style questions with instant explanations, flashcards and spaced review.
Study 3.6 free in APrep