📚Study Guide: Iteration
Unit 4: Iteration
Iteration--repeating a block of code--is one of the most powerful concepts in programming. This unit covers while loops, for loops, and the enhanced for loop (for-each), as well as the critical skills of loop tracing and determining loop bounds. Students must understand when to use each loop type: while loops for indefinite iteration (when the number of repetitions is unknown), for loops for definite iteration with a counter, and enhanced for loops for iterating through arrays and ArrayLists without index manipulation. The AP exam extensively tests loop tracing, often presenting nested loops and asking students to compute final variable values or output patterns. Understanding off-by-one errors--whether a loop runs one time too many or too few--is essential for writing correct code. The break statement exits a loop immediately; the continue statement skips the rest of the current iteration and proceeds to the next. Loop invariants, conditions that remain true before and after each iteration, are useful for reasoning about correctness. Students must also be able to convert between equivalent while and for loops. Infinite loops occur when the termination condition never becomes false, a common bug that the AP exam frequently presents in tracing questions.
Key Concepts
- while Loop: while (condition) { body; } Checks condition BEFORE each iteration. Use when the number of iterations is not known in advance. Risk of infinite loop if condition never becomes false.
- for Loop: for (init; condition; update) { body; } Compact structure for counter-controlled loops. The init runs once, condition is checked before each iteration, and update runs after each iteration. All three parts are optional.
- Enhanced for Loop (for-each): for (Type element : collection) { body; } Iterates over each element in an array or ArrayList. No index variable; cannot modify the collection structure (add/remove) during iteration. Use when you only need to access elements.
- Nested Loops: A loop inside another loop. The inner loop completes all iterations for each single iteration of the outer loop. Common for processing 2D arrays and generating patterns.
- Loop Control Statements: break exits the nearest enclosing loop. continue skips the rest of the current iteration and moves to the next.
- Infinite Loops: Occur when the loop condition never evaluates to false. Common causes: forgetting to update the loop variable, incorrect comparison operator, or logical error in condition.
Vocabulary
- Iteration: The repetition of a process or set of instructions in a program.
- Loop Variable: A variable, often called a counter or index, that controls the number of times a loop executes and is typically updated each iteration.
- Off-By-One Error: A logical error in which a loop iterates one time too many or one time too few, usually due to incorrect initialization or boundary condition.
- Sentinel Value: A special input value that signals the termination of a loop when its exact number of iterations is unknown.
- Nested Loop: A loop that is placed inside the body of another loop, creating multiple levels of iteration.
- Infinite Loop: A loop that lacks a proper termination condition and therefore repeats indefinitely.
Essential Formulas / Syntax Patterns
- for (int i = 0; i < n; i++) { ... } // runs n times
- for (int i = 1; i <= n; i++) { ... } // runs n times
- for (int i = n - 1; i >= 0; i--) { ... } // reverse iteration
- for (String s : list) { ... } // for-each loop
- while (sc.hasNext()) { ... } // indefinite iteration
Common Mistakes
- Off-By-One Errors: for (int i = 0; i <= arr.length; i++) causes ArrayIndexOutOfBoundsException. The last valid index is arr.length - 1.
- Infinite Loops: for (int i = 0; i < 10; ) { ... } never increments i. Ensure the update expression modifies the loop variable toward the termination condition.
- Modifying a Collection in Enhanced for: Adding or removing elements from an ArrayList while iterating with a for-each loop causes a ConcurrentModificationException.
- Confusing break and continue: break exits the loop entirely. continue skips to the next iteration. They affect only the innermost loop in nested structures.
AP Exam Strategies
- Trace Loops with a Table: Create a table with columns for iteration number, loop variable value, and any modified variables. This prevents mental arithmetic errors.
- Count Iterations Before Tracing: Determine exactly how many times the loop will run by examining the init, condition, and update.
- Watch for Nested Loops: In nested loops, the total number of iterations is the product of the iterations of each loop (if independent).
- Check Array Bounds in Loops: Any loop accessing an array or ArrayList must ensure the index stays within [0, length-1] or [0, size()-1].
Real-World Applications
- Data Processing: Loops iterate over millions of records in databases and spreadsheets to calculate totals, averages, and summaries.
- Simulation Engines: Physics and financial simulations use nested loops to model interactions between particles or assets over time steps.
- Image Processing: Nested loops traverse every pixel in an image to apply filters, blur, edge detection, or color adjustments.