Unit 2 Cycle 2 Day 23: Loop with Early Return Pattern
Share
Loop with Early Return Pattern
Section 2.10 — Loop Algorithms
Key Concept
A loop with an early return pattern exits the method (not just the loop) when a specific condition is found. The pattern for (int i = 0; i < n; i++) { if (condition) return result; } returns immediately upon finding the first match. If no match is found, execution continues after the loop to a default return. The AP exam tests this in methods that search for values: the key is understanding that return exits the entire method, and any code after the return statement in the same block is unreachable.
Consider the following method.
What does isPrime(15) return?
Answer: (B) false
15 > 1, so we enter the loop. i=2: 15%2=1, not 0. i=3: 15%3=0, return false immediately. 15 is divisible by 3, so it is not prime.
Why Not the Others?
(A) 15 = 3 * 5, so it has divisors other than 1 and itself. It is not prime.
(C) No error occurs. The method handles all positive integers correctly.
(D) The method has a return statement inside the loop that guarantees termination.
Common Mistake
The early return pattern exits the method as soon as a divisor is found. The loop does not need to check all values up to n. Finding one divisor is sufficient to conclude the number is not prime.
AP Exam Tip
Early return in loops is efficient. Once you find what you are looking for, return immediately. The return true after the loop executes only if NO divisor was found.