AP Computer Science A › Unit 2
Programs make decisions and repeat steps. This unit covers Boolean expressions, if and nested if statements, compound conditions, while and for loops, nested loops, and standard algorithms on numbers and strings. Expect to trace loops, count how many times a statement runs, and apply De Morgan's laws to rewrite conditions. Free-response questions ask you to write methods that combine loops and conditionals correctly. Off-by-one errors are the most common mistake, especially with loop bounds and string indexes. Students also overlook short-circuit evaluation in compound conditions.
These are taken from the Regular set, with the answer and explanation shown.
1. Consider the following code segment, where x and flag are properly declared and x is an int.
Answer: B. A comparison already gives true or false, so flag = x > 0; stores the same value as the if-else. x >= 0 differs at 0. !(x > 0) and x < 0 give the opposite for positive values.
Common trap: Choosing x >= 0. It gives true for 0, but the original code gives false for 0.
2. The following code segment is intended to print the integers from 1 through 5, separated by spaces.
Answer: B. The loop must keep going while i is at most 5, so the condition is i <= n. The other three conditions are false when i is 5, so they stop after printing 4. That is an off-by-one error.
Common trap: Choosing i < n. It looks normal, but here i starts at 1, so < drops the last value.
3. What is printed as a result of executing the following code segment?
Answer: D. The inner loop starts at j = i. It runs 5 times when i is 1, 4 times when i is 2, and so on down to 1 time when i is 5. The total is 5 + 4 + 3 + 2 + 1 = 15.
Common trap: Choosing 25 by multiplying 5 × 5. The inner loop does not always run 5 times.