AP Computer Science A study materials
AP Computer Science A study resources

AP Computer Science A: Selection and Iteration

AP Computer Science A · Work through your exam, one topic at a time.

All guide sections

Selection and Iteration

What you must know

Selection uses if, else if, and else, plus the short-circuit logical operators && and ||. Know that && stops evaluating once a false operand is found and || stops at the first true operand-this matters when a later operand would throw an exception (e.g., a null check). Understand boolean expressions, De Morgan's laws (!(a && b) equals !a || !b), and operator precedence: ! binds tightest, then &&, then ||. Comparison operators and equals produce booleans.

Iteration uses while, for, and enhanced for loops. For a for loop, know the three parts (initialization, condition, update) and the exact order of execution. Trace loops by building a table of variable values per iteration. Understand nested loops and how the inner loop resets each time the outer loop repeats.

Traps

  • Off-by-one errors: does the loop run while i < n or i <= n?
  • else if chains execute at most one branch; separate if statements can execute multiple branches.
  • The enhanced for loop cannot modify array elements through its loop variable (it copies the value).
  • Infinite loops from a missing or wrong update statement.
  • Confusing = (assignment) with == (comparison).

Rule of thumb

When tracing a loop, write a column for each variable plus the loop counter and fill in one row per iteration. Stop when the condition first becomes false.

Worked example: for (int i = 0; i < 4; i++) { if (i % 2 == 0) sum += i; } adds 0 + 2, so sum ends at 2.