Topic 2.8 - For Loops in Java

Foundations of For Loops and Iteration

  • Definition of Iteration:

    • In Java programming, a loop represents an iterative statement used to repeat a specific block of statements multiple times until a terminating condition is reached.

    • A for loop is typically utilized when the exact number of iterations is known prior to entering the loop body, serving as a structured counter-driven control mechanism.

  • Conceptual Parallels to Visual Programming Environments:

    • Visual, block-based educational programming environments utilize simplified looping constructs:

    • In Scratch and Snap!, bounded repetition is handled using the explicit repeat(n) block, which iterates an enclosed stack of commands precisely nn times.

    • In App Inventor, counting iteration is handled via the for each ... from ... to ... by ... do block, where a programmer specifies an explicit iteration variable, start value, end bound, and increment step.

  • App Inventor vs. Java Syntax Comparison:

    • In App Inventor, the block defines: for each [number] from [1] to [5] by [1] do [block of statements].

    • In Java, the equivalent functionality is implemented using standard syntax: java for (int number = 1; number <= 5; number++) { block of statements; } &nbsp;&nbsp;&nbsp;&nbsp;

Figure 2.8.1: Comparison of App Inventor for-each loop block and equivalent Java for loop

Anatomy and Structure of a For Loop

  • Three Essential Components of a For Loop Header:

    • A standard Java for loop consolidates all three control actions required for counter-controlled repetition into a single header line:

    1. Initialization: Declares and sets the starting value of the loop control variable (counter). This executes once before any condition evaluation.

    2. Boolean Condition (Test): A relational expression evaluated before each iteration. The loop body executes if and only if this expression evaluates to true.

    3. Update (Increment/Decrement): Modifies the loop control variable after each execution of the loop body, before the condition is re-evaluated.

    • The three expressions are enclosed within parentheses and separated from one another by semicolons (;).

  • General Syntax Format:java for (initialize; test; update) { loop body } &nbsp;&nbsp;

  • Step-by-Step Control Flow Execution Lifecycle:

    • Step 1: Execute the Initialization statement. This creates/initializes the loop control variable in memory.

    • Step 2: Evaluate the Boolean Condition.

    • If true, proceed to Step 3.

    • If false, terminate the loop immediately and transfer execution flow to the statement directly following the loop body.

    • Step 3: Execute the statements contained inside the Loop Body from top to bottom.

    • Step 4: Execute the Update statement to adjust the loop control variable.

    • Step 5: Loop back to Step 2 to re-evaluate the Boolean condition.

Figure 2.8.3: Flowchart illustrating the control flow of a for loop

Equivalence Between For Loops and While Loops

  • Structural Mapping:

    • Every for loop can be rewritten into an equivalent while loop, and every while loop can be converted into a for loop.

    • The components map as follows:

    • The for loop initialization statement is placed immediately preceding the while statement.

    • The for loop test condition serves directly as the while (condition) expression.

    • The for loop update statement is placed at the very end of the while loop body, ensuring it runs after all primary operations but before condition re-evaluation.

  • Comparative Code Walkthrough:

    • For Loop Representation:java for (int x = 3; x > 0; x--) { System.out.println(x); } &nbsp;&nbsp;&nbsp;&nbsp;

  • Equivalent While Loop Representation:java int x = 3; while (x > 0) { System.out.println(x); x = x - 1; } &nbsp;&nbsp;&nbsp;&nbsp;

Figure 2.8.2: Mapping of Java for loop components to an equivalent while loop
  • Interactive Loop Conversion Exercises:

    • Activity 2.8.1 (Count Range Modification):

    • Original task: Given a loop counting from 11 to 55, adapt the header to count from 22 to 1010.

    • Solution: Set initialization to int i = 2, test condition to i <= 10, and update to i++.

    • Activity 2.8.2 (While to For Conversion):

    • Target: Convert a while loop that counts from 55 to 1010 into a concise for loop.

    • Implementation: java for (int i = 5; i <= 10; i++) { System.out.println(i); } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

Standard Patterns, Indexing Conventions, and Execution Tracing

  • Counter Variable Naming Convention:

    • The identifier i (representing index) is traditionally and predominantly used as the counter variable in loops.

  • Two Primary Idiomatic Counting Patterns:

    • Both of the following standard patterns iterate precisely 1010 times:

    • Zero-Indexed Pattern (Using Strict Inequality <):java for (int i = 0; i < 10; i++) { System.out.println(i); } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

    • Useful when indexing arrays and zero-indexed data collections.

    • Prints values: 0,1,2,3,4,5,6,7,8,90, 1, 2, 3, 4, 5, 6, 7, 8, 9.

  • One-Indexed Pattern (Using Inclusive Inequality <=):java for (int i = 1; i <= 10; i++) { System.out.println(i); } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

    • Useful when natural counting numbers (11 through NN) are needed.

    • Prints values: 1,2,3,4,5,6,7,8,9,101, 2, 3, 4, 5, 6, 7, 8, 9, 10.

  • Calculating Iteration Counts (The Inclusivity Formula):

    • When a loop starts at integer start, increments by 11, and ends at integer end using an inclusive condition (<=):     Total Iterations=end−start+1\text{Total Iterations} = \text{end} - \text{start} + 1

    • When a loop uses a strict upper bound (<):     Total Iterations=end−start\text{Total Iterations} = \text{end} - \text{start}

  • Detailed Activity Code Traces:

    • Activity 2.8.3 (Trace of Bounded Count):

    • Segment: java for (int i = 3; i < 8; i++) { System.out.print(i + " "); } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

    • Correct Output: 3 4 5 6 7

    • Distractor Analysis:

    • 3 4 5 6 7 8: Incorrect; the loop stops immediately when i=8i = 8, so the final value output is 77.

    • 0 1 2 3 4 5 6 7 8: Incorrect; ii initializes at 33, not 00.

    • 8 8 8 8 8: Incorrect; this would occur only if the loop lacked an update expression, but i++ guarantees incrementation.

  • Activity 2.8.4 (Trace of Inclusive Upper Bound):

    • Segment: java for (int i = 1; i <= 10; i++) { System.out.print(i + " "); } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

    • Correct Output: 1 2 3 4 5 6 7 8 9 10

    • Distractor Analysis:

    • 3 4 5 6 7 8: Incorrect initialization value.

    • 0 1 2 3 4 5 6 7 8 9: Incorrect initialization (00 instead of 11).

    • 1 3 5 7 9: Incorrect; counter updates by +1+1 each iteration, not by +2+2.

  • Activity 2.8.5 (Execution Count Verification):

    • Segment: java for (int i = 3; i <= 9; i++) { System.out.print("*"); } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

    • Question: How many times does the loop print a *?

    • Calculation: Iterations=9−3+1=7\text{Iterations} = 9 - 3 + 1 = 7.

    • Correct Answer: 77

    • Distractor Analysis:

    • 1010: Occurs if ii begins at 00 and iterates to 99 inclusive.

    • 66: Arithmetic error from failing to include the initial element (9−3=69 - 3 = 6).

    • 99: Occurs if ii begins at 00 with an exclusive bound of 99.

  • Activity 2.8.6 (Parsons Problem - Even Number Generator):

    • Objective: Arrange code blocks to print all even values from 00 to 1010.

    • Key Java Best Practice: Although Java syntax does not enforce whitespace indentation for code validity, proper visual indentation inside block delimiters ({ }) is an essential professional habit for readability.

Decrementing Loops and Non-Unit Step Sizes

  • Mechanics of Decrementing Loops:

    • Loops can count backwards from a larger starting number down to a lower bound (00 or 11).

    • Counting backwards requires modifying all three parts of the loop header:

    1. Initialize the counter variable to the higher starting boundary value.

    2. Use a greater-than or greater-than-or-equal-to comparison operator (> or >=) to check the lower bound.

    3. Use a decrement operator (-- or -= step) in the update section.

    • Canonical Example: java for (int i = 5; i > 0; i--) &nbsp;&nbsp;&nbsp;&nbsp;

    • Traces through values: 5,4,3,2,15, 4, 3, 2, 1.

    • Terminates when ii reaches 00.

  • Activity 2.8.7 (printPopSong Trace and Visualization):

    • Context: The method printPopSong prints verses using a decrementing loop.

    • Variable Lifecycle:

    • Sets i=5i = 5.

    • Verifies 5>05 > 0 (true), executes song body.

    • Decrements ii by 11.

    • Continues until i=0i = 0, at which point the Boolean expression evaluates to false and the loop exits.

    • Modification: Changing the initialization line to int i = 3 shortens execution to start from verse 33.

  • Activity 2.8.8 (Backwards Counting by Twos):

    • Objective: Print out the sequence 5 3 1.

    • Implementation Strategy:

    • Initialization: int i = 5;

    • Condition: i >= 1; or i > 0;

    • Update: i -= 2

    • Header: java for (int i = 5; i >= 1; i -= 2) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

Geometric Applications: Turtle Graphics and Polygon Drawing

  • Mathematical Foundations of Regular Polygons:

    • To draw a closed regular polygon of nn sides, a Turtle agent traverses each edge and turns by the exterior angle at each vertex.

    • Total Exterior Angle Sum Theorem:

    • The sum of all exterior turning angles for any simple closed convex polygon is always identically 360∘360^{\circ}.

    • For an nn-sided regular polygon with equal sides and angles, the exterior turn angle formula is:       Turn Angle=360∘n\text{Turn Angle} = \frac{360^{\circ}}{n}

  • Turtle Graphics Implementation Breakdown:

    • drawSquare(Turtle t):

    • Number of iterations: 44

    • Exterior angle calculation: 360∘4=90∘\frac{360^{\circ}}{4} = 90^{\circ}

    • Loop header: for (int i = 0; i < 4; i++)

    • drawTriangle(Turtle t) (Equilateral Triangle):

    • Number of iterations: 33

    • Exterior angle calculation: 360∘3=120∘\frac{360^{\circ}}{3} = 120^{\circ}

    • Loop header: for (int i = 0; i < 3; i++)

    • drawPentagon(Turtle t):

    • Number of iterations: 55

    • Exterior angle calculation: 360∘5=72∘\frac{360^{\circ}}{5} = 72^{\circ}

    • Loop header: for (int i = 0; i < 5; i++)

    • drawPolygon(Turtle t, int n, int pixels) (Generalization):

    • Takes parameters nn (number of sides) and pixels (forward edge length).

    • Executes loop nn times.

    • Turns the turtle by 360.0n\frac{360.0}{n} degrees at each step.

    • Hexagon Demonstration:

    • Passing argument n=6n = 6 produces a hexagon with turns equal to 360∘6=60∘\frac{360^{\circ}}{6} = 60^{\circ}.

  • Software Design Principle (Abstraction):

    • Parameterizing the polygon procedure with nn demonstrates the power of procedural abstraction: a single generalized method draws an infinite variety of shapes simply by altering argument values.

    • Practical Caveat: If the turtle collides with display screen boundaries, forward motion is arrested, distorting the intended geometry. Mitigate this by repositioning the turtle or selecting smaller pixels values.

Official AP Computer Science A Standards and Review

  • Curricular Specifications:

    • AP 2.8.A.1: A for loop is an iterative statement. A standard for loop header contains three distinct sections: the initialization of the loop control variable, the Boolean expression testing the variable, and the update statement modifying the variable.

    • AP 2.8.A.2: In a for loop, the initialization statement is executed exactly once before the first evaluation of the Boolean condition. The Boolean expression is tested immediately after initialization and then evaluated before each subsequent iteration. In every iteration, the update statement executes after the complete loop body has executed and immediately before the condition is re-evaluated.

    • AP 2.8.A.3: A for loop can be rewritten into an equivalent while loop, and vice versa.

  • Advanced Practice Activity Traces:

    • Activity 2.8.10 (Comprehensive Loop Equivalence Analysis):

    • Baseline Code Segment:java int count = 0, sum = 0; while (count <= 6) { count++; if (count % 2 == 0) { sum += count; } } System.out.println(sum); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Trace of Baseline Segment:

    • Iteration 1: count becomes 11. 1%2≠01 \% 2 \neq 0.

  • Iteration 2: count becomes 22. 2%2==02 \% 2 == 0; sum becomes 0+2=20 + 2 = 2.

  • Iteration 3: count becomes 33. 3%2≠03 \% 2 \neq 0.

  • Iteration 4: count becomes 44. 4%2==04 \% 2 == 0; sum becomes 2+4=62 + 4 = 6.

  • Iteration 5: count becomes 55. 5%2≠05 \% 2 \neq 0.

  • Iteration 6: count becomes 66. 6%2==06 \% 2 == 0; sum becomes 6+6=126 + 6 = 12.

  • Iteration 7: count is 6≤66 \le 6 (true). count becomes 77. 7%2≠07 \% 2 \neq 0.

    • Exit: count is now 7≤67 \le 6 (false). Final sum printed: 1212.

  • Candidate Implementations:

    • Candidate I:java int sum = 0; for (int count = 0; count <= 6; count++) { count++; if (count % 2 == 0) { sum += count; } } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

    • Evaluation: Incorrect. Candidate I contains an extra count++ inside the loop body, causing count to double-increment each cycle (+1+1 in body, +1+1 in header).

  • Candidate II: java int sum = 0; for (int i = 0; i <= 6; i += 2) { sum += i; } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

    • Evaluation: Correct. Counter visits even values 0,2,4,60, 2, 4, 6. sum = 0+2+4+6=120 + 2 + 4 + 6 = 12.

  • Candidate III: java int sum = 0; for (int j = 7; j > 1; j--) { if (j % 2 == 0) { sum += j; } } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

    • Evaluation: Correct. Variable jj counts down through 7,6,5,4,3,27, 6, 5, 4, 3, 2. Even numbers 6,4,26, 4, 2 are summed: 6+4+2=126 + 4 + 2 = 12.

      • Conclusion: II and III only yield identical output (1212).

  • Activity 2.8.11 (Step-Size Modification and Product Accumulator):

    • Original Code Segment:java int result = 1; for (int i = 3; i < 6; i += 2) { result *= i; } System.out.println(result); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

    • Trace: i=3i = 3 (condition 3<63 < 6 true), result = 1×3=31 \times 3 = 3. Update: i=5i = 5 (condition 5<65 < 6 true), result = 3×5=153 \times 5 = 15. Update: i=7i = 7 (condition 7<67 < 6 false).

    • Loop executes 22 iterations and outputs 1515.

  • Modified Header: for (int i = 4; i <= 6; i += 2)

    • Trace: i=4i = 4 (condition 4≤64 \le 6 true), result = 1×4=41 \times 4 = 4. Update: i=6i = 6 (condition 6≤66 \le 6 true), result = 4×6=244 \times 6 = 24. Update: i=8i = 8 (condition 8≤68 \le 6 false).

    • Loop executes 22 iterations and outputs 2424.

  • Correct Analysis: The output will be different, but both versions of the loop will iterate two times. The original multiplies odd values (3×53 \times 5) while the modified version multiplies even values (4×64 \times 6).