Unit 2: Selection & Iteration

If/else, loops, and the code-tracing skill that decides your MC score.

25–35% of the AP CSA exam — the biggest single unit

Home → Unit 2

Tracing is the skill. Everything else is details.

The MC section is full of "what does this print?" questions. The only reliable technique is a trace table: write down every variable, update it line by line, no shortcuts. Students who trace on paper score higher. Every time.

The loop that looks scary but isn't

int sum = 0;
for (int i = 1; i <= 4; i++) {
    sum += i * 2;
}
System.out.println(sum);   // trace it: 2, 6, 12, 20 → prints 20

Trace: i=1 → sum=2. i=2 → sum=6. i=3 → sum=12. i=4 → sum=20. i=5 fails the test, loop ends. That's the whole method — boring, mechanical, and worth a pile of points.

How many times does it run?

For for (int i = a; i < b; i++), the loop body runs b − a times. With <=, it's b − a + 1. This one formula answers several MC questions per exam.

Short-circuit evaluation

// If x is 0, Java never evaluates the right side —
// the && already knows the answer is false.
if (x != 0 && total / x > 2) { ... }   // safe: no divide-by-zero

De Morgan's — the exam's favorite disguise

!(a && b)   // is the same as   !a || !b
!(a || b)   // is the same as   !a && !b

Flip the operator, negate each piece. If an answer choice negates a compound condition without flipping &&/||, it's wrong.

Try it — exam-style questions

1. What does this print?
int x = 10;
while (x > 3) {
    x -= 3;
}
System.out.println(x);
2. How many times does the body execute?
for (int k = 3; k <= 11; k += 2) {
    // body
}
3. Which expression is equivalent to !(score >= 60 && passed)?
4. What does this nested loop print?
for (int i = 1; i <= 3; i++) {
    for (int j = i; j <= 3; j++) {
        System.out.print("*");
    }
}

⚠ Common mistakes that cost points

Loops still feel like guesswork?

Tracing is a learnable skill — it just needs someone watching you do it and catching the bad habits. That's exactly what tutoring sessions are for.

Ask about tutoring →