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
forloop 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 times.In App Inventor, counting iteration is handled via the
for each ... from ... to ... by ... doblock, 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; }

Anatomy and Structure of a For Loop
Three Essential Components of a For Loop Header:
A standard Java
forloop consolidates all three control actions required for counter-controlled repetition into a single header line:
Initialization: Declares and sets the starting value of the loop control variable (counter). This executes once before any condition evaluation.
Boolean Condition (Test): A relational expression evaluated before each iteration. The loop body executes if and only if this expression evaluates to
true.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 } 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.

Equivalence Between For Loops and While Loops
Structural Mapping:
Every
forloop can be rewritten into an equivalentwhileloop, and everywhileloop can be converted into aforloop.The components map as follows:
The
forloop initialization statement is placed immediately preceding thewhilestatement.The
forloop test condition serves directly as thewhile (condition)expression.The
forloop update statement is placed at the very end of thewhileloop 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); }
Equivalent While Loop Representation:
java int x = 3; while (x > 0) { System.out.println(x); x = x - 1; }

Interactive Loop Conversion Exercises:
Activity 2.8.1 (Count Range Modification):
Original task: Given a loop counting from to , adapt the header to count from to .
Solution: Set initialization to
int i = 2, test condition toi <= 10, and update toi++.Activity 2.8.2 (While to For Conversion):
Target: Convert a
whileloop that counts from to into a conciseforloop.Implementation:
java for (int i = 5; i <= 10; i++) { System.out.println(i); }
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 times:
Zero-Indexed Pattern (Using Strict Inequality
<):java for (int i = 0; i < 10; i++) { System.out.println(i); } Useful when indexing arrays and zero-indexed data collections.
Prints values: .
One-Indexed Pattern (Using Inclusive Inequality
<=):java for (int i = 1; i <= 10; i++) { System.out.println(i); } Useful when natural counting numbers ( through ) are needed.
Prints values: .
Calculating Iteration Counts (The Inclusivity Formula):
When a loop starts at integer
start, increments by , and ends at integerendusing an inclusive condition (<=):When a loop uses a strict upper bound (
<):
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 + " "); } Correct Output:
3 4 5 6 7Distractor Analysis:
3 4 5 6 7 8: Incorrect; the loop stops immediately when , so the final value output is .0 1 2 3 4 5 6 7 8: Incorrect; initializes at , not .8 8 8 8 8: Incorrect; this would occur only if the loop lacked an update expression, buti++guarantees incrementation.
Activity 2.8.4 (Trace of Inclusive Upper Bound):
Segment:
java for (int i = 1; i <= 10; i++) { System.out.print(i + " "); } Correct Output:
1 2 3 4 5 6 7 8 9 10Distractor Analysis:
3 4 5 6 7 8: Incorrect initialization value.0 1 2 3 4 5 6 7 8 9: Incorrect initialization ( instead of ).1 3 5 7 9: Incorrect; counter updates by each iteration, not by .
Activity 2.8.5 (Execution Count Verification):
Segment:
java for (int i = 3; i <= 9; i++) { System.out.print("*"); } Question: How many times does the loop print a
*?Calculation: .
Correct Answer:
Distractor Analysis:
: Occurs if begins at and iterates to inclusive.
: Arithmetic error from failing to include the initial element ().
: Occurs if begins at with an exclusive bound of .
Activity 2.8.6 (Parsons Problem - Even Number Generator):
Objective: Arrange code blocks to print all even values from to .
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 ( or ).
Counting backwards requires modifying all three parts of the loop header:
Initialize the counter variable to the higher starting boundary value.
Use a greater-than or greater-than-or-equal-to comparison operator (
>or>=) to check the lower bound.Use a decrement operator (
--or-= step) in the update section.
Canonical Example:
java for (int i = 5; i > 0; i--) Traces through values: .
Terminates when reaches .
Activity 2.8.7 (
printPopSongTrace and Visualization):Context: The method
printPopSongprints verses using a decrementing loop.Variable Lifecycle:
Sets .
Verifies (
true), executes song body.Decrements by .
Continues until , at which point the Boolean expression evaluates to
falseand the loop exits.Modification: Changing the initialization line to
int i = 3shortens execution to start from verse .
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;ori > 0;Update:
i -= 2Header:
java for (int i = 5; i >= 1; i -= 2)
Geometric Applications: Turtle Graphics and Polygon Drawing
Mathematical Foundations of Regular Polygons:
To draw a closed regular polygon of 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 .
For an -sided regular polygon with equal sides and angles, the exterior turn angle formula is:
Turtle Graphics Implementation Breakdown:
drawSquare(Turtle t):Number of iterations:
Exterior angle calculation:
Loop header:
for (int i = 0; i < 4; i++)drawTriangle(Turtle t)(Equilateral Triangle):Number of iterations:
Exterior angle calculation:
Loop header:
for (int i = 0; i < 3; i++)drawPentagon(Turtle t):Number of iterations:
Exterior angle calculation:
Loop header:
for (int i = 0; i < 5; i++)drawPolygon(Turtle t, int n, int pixels)(Generalization):Takes parameters (number of sides) and
pixels(forward edge length).Executes loop times.
Turns the turtle by degrees at each step.
Hexagon Demonstration:
Passing argument produces a hexagon with turns equal to .
Software Design Principle (Abstraction):
Parameterizing the polygon procedure with 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
pixelsvalues.
Official AP Computer Science A Standards and Review
Curricular Specifications:
AP 2.8.A.1: A
forloop is an iterative statement. A standardforloop 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
forloop, 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
forloop can be rewritten into an equivalentwhileloop, 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);
Trace of Baseline Segment:
Iteration 1:
countbecomes . .
Iteration 2:
countbecomes . ;sumbecomes .Iteration 3:
countbecomes . .Iteration 4:
countbecomes . ;sumbecomes .Iteration 5:
countbecomes . .Iteration 6:
countbecomes . ;sumbecomes .Iteration 7:
countis (true).countbecomes . .Exit:
countis now (false). Finalsumprinted: .
Candidate Implementations:
Candidate I:
java int sum = 0; for (int count = 0; count <= 6; count++) { count++; if (count % 2 == 0) { sum += count; } } Evaluation: Incorrect. Candidate I contains an extra
count++inside the loop body, causingcountto double-increment each cycle ( in body, in header).
Candidate II:
java int sum = 0; for (int i = 0; i <= 6; i += 2) { sum += i; } Evaluation: Correct. Counter visits even values .
sum= .
Candidate III:
java int sum = 0; for (int j = 7; j > 1; j--) { if (j % 2 == 0) { sum += j; } } Evaluation: Correct. Variable counts down through . Even numbers are summed: .
Conclusion: II and III only yield identical output ().
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); Trace: (condition
true),result= . Update: (conditiontrue),result= . Update: (conditionfalse).Loop executes iterations and outputs .
Modified Header:
for (int i = 4; i <= 6; i += 2)Trace: (condition
true),result= . Update: (conditiontrue),result= . Update: (conditionfalse).Loop executes iterations and outputs .
Correct Analysis: The output will be different, but both versions of the loop will iterate two times. The original multiplies odd values () while the modified version multiplies even values ().