Skip to main content
← Unit 3: Algorithms and Programming

Code Scholars Tutoring · AP Computer Science Principles

3.1 Sequencing, Selection, and Iteration

How it works

Algorithms combine ordered steps, decisions, and repetition to solve problems.

Trace each branch condition and each loop update before deciding what is displayed or returned.

Common error

A loop may run zero times, one time, or more times depending on the initial values.

Worked example

Trace pseudocode using AP CSP assignment and condition rules.

Data / pseudocode

x <- 2
REPEAT 3 TIMES {
  x <- x + 2
  IF (x > 5) { DISPLAY(x) }
}
Read stateUpdateTest conditionProduce output
Read state → Update → Test condition → Produce output

The successive x values are 4, 6, and 8. Only 6 and 8 satisfy the condition, so those values are displayed in that order. The update occurs before each test inside the loop.

Exercises

3.1.1

Trace: total <- 0; FOR EACH n IN [2, 5, 4] { IF (n > 3) { total <- total + n } }; DISPLAY(total).

Show solution

2 is skipped. 5 changes total to 5, and 4 changes it to 9. The displayed value is 9.

3.1.2

Write pseudocode that displays the even integers from 2 through 8 inclusive.

Show solution

Solution pseudocode

n <- 2
REPEAT 4 TIMES {
  DISPLAY(n)
  n <- n + 2
}
The output is 2, 4, 6, 8.

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic