Selection and iteration
Write Java conditions and loops
Trace short-circuit conditions, loop bounds, and repeated calculations.
Examples use Java. Read and trace them here; run them in a Java environment. The studio executes pseudocode.
Separate the condition from the update
A for loop initializes a counter, checks its condition before each iteration, and applies its update after the body. With i < 4, the values 0, 1, 2, and 3 enter the body. Changing < to <= adds an iteration and may cause an array index error.
A total accumulates values, while a count records how many values satisfy a condition. Initialize both before the loop. In the example, only even i values contribute to the total, so the output is 6.
public class Demo {
public static void main(String[] args) {
int total = 0;
for (int i = 1; i <= 4; i++) {
if (i % 2 == 0) {
total += i;
}
}
System.out.println(total);
}
}Use short-circuit evaluation
In a && b, Java evaluates b only if a is true. In a || b, it evaluates b only if a is false. A guard such as index < values.length && values[index] != 0 checks the bound before accessing the array.
For nested loops, count how many times the inner body runs for each outer value. If each of n rows scans n columns, the body runs n squared times. Doubling n approximately quadruples that work.
Check yourself
Why must the bounds check come before an array access in an && condition?Show answer
Short-circuiting skips the access when the bounds check is false. Reversing the order can access an invalid index first.
References used to build these lessons
We used these official documents as references when building this course's lessons. They are the sources for the syllabus structure and course requirements.
College Board · Effective fall 2025