From the free course AP Computer Science A on Lykke
2.8 for Loops
Key concepts: for-loop syntax and iteration · nested for loops · row-major and column-major traversal of 2D arrays · enhanced for loops · array modification limitations with enhanced for loops · loop counters and accumulator variables · variable scope within curly-brace blocks · loop initialization and termination conditions · traversing ArrayLists with for loops · using loops to search and update array elements
A for loop is a compact way to repeat an action while a counter moves through a predictable range. Its three-part header answers three questions in order: Where does the counter start?
2.8 for Loops
A for loop is a compact way to repeat an action while a counter moves through a predictable range. Its three-part header answers three questions in order: Where does the counter start? When should repetition continue? How does the counter change?
for (int i = 0; i < 5; i++)
{
System.out.println(i);
}
The execution pattern is:
initialize i = 0
↓
test i < 5 ── false ──→ stop
│ true
↓
run loop body
↓
update i++
└──────────────→ test again
The output is 0, 1, 2, 3, and 4. The counter reaches 5, but the body does not run for i = 5 because the condition is tested before each iteration. A common misconception is that the upper bound is included; in i < 5, it is not.
Counters, accumulators, and scope
A counter tracks position or repetition count. An accumulator preserves a growing result, such as a total or rank. Any variable whose value must survive from one iteration to the next must be declared before the loop.
int rank = 1;
for (int i = 0; i < competitorList.size() / 2 + 1; i++)
{
System.out.println("Rank " + rank);
rank++;
}
Here, rank is initialized once, used during each iteration, and increased with rank++. If rank were declared inside the loop, it would be recreated on every pass and would repeatedly return to its initial value. The bound competitorList.size() / 2 + 1 is recalculated from the number of elements in the ArrayList; because valid indexes stop at size() - 1, the loop must be checked carefully for the intended number of elements.
Java also restricts a variable to the scope—the region of code where that name is accessible—of the block in which it is declared.
int start = useLater ? 2 : 0;
if (useLater)
{
start = 2;
}
for (int i = start; i < 6; i++)
{
System.out.println(i);
}
The first declaration guarantees that start receives a value on every path. Java’s definite-assignment rule requires a local variable to be assigned before it is used. Declaring start only inside if (useLater) and then using it afterward causes a compile-time error when useLater is false. Another valid design is to place the for loop inside the if block.
Nested loops and 2D arrays
A 2D array is naturally traversed with nested loops: the outer loop chooses a row, and the inner loop visits positions within that row.
Row-major order completes one row before moving to the next row.
for (int row = 0; row < numRows; row++)
{
for (int col = 0; col < numCols; col++)
{
process(puzzle[row][col]);
}
}
For a $3 \times 4$ array, the access order begins
(0,0) → (0,1) → (0,2) → (0,3)
↓
(1,0) → (1,1) → (1,2) → (1,3)
↓
(2,0) → (2,1) → (2,2) → (2,3)
Column-major order reverses the roles: the outer loop chooses a column, and the inner loop moves down that column.
for (int col = 0; col < numCols; col++)
{
for (int row = 0; row < numRows; row++)
{
process(puzzle[row][col]);
}
}
Row-major traversal visits (0,0), (0,1), (1,0). Column-major traversal visits (0,0), (1,0), (0,1). The same elements are visited, but the order can change the result whenever the operation depends on sequence.
Updating every cell
Standard loops provide indexes, so they can both read and modify array elements. For example, each cell of puzzle can receive a random integer from $1$ through $9$:
for (int row = 0; row < numRows; row++)
{
for (int col = 0; col < numCols; col++)
{
puzzle[row][col] = (int) (Math.random() * 9) + 1;
}
}
Math.random() * 9 produces a value from $0$ up to, but not including, $9$. Casting to int discards the fractional part, producing an integer from $0$ through $8; adding 1` shifts the range to $1$ through $9$.
Enhanced for loops
An enhanced for loop visits each element without exposing an index:
String[] names = {"Ari", "Bo", "Cy"};
for (String name : names)
{
System.out.println(name);
}
This is excellent when the task is simply “process every element.” However, name is not an index and assigning a new value to it does not replace the corresponding array element:
for (String name : names)
{
name = "Guest"; // changes only the local loop variable
}
To modify the original array, use a standard loop:
for (int i = 0; i < names.length; i++)
{
names[i] = "Guest";
}
Nested enhanced loops can traverse a 2D array because the outer variable represents a row and the inner variable represents an element in that row. They remain less suitable when indexes are needed for assignment, position reporting, or controlled traversal. Also remember that return exits the entire method immediately, not merely the current loop.
Retrieval check
For the code below, identify the traversal order and the final value of count.
int count = 0;
for (int col = 0; col < 3; col++)
{
for (int row = 0; row < 2; row++)
{
count++;
}
}
Answer: column-major order, because the column loop is outermost; count finishes at $6$, because the body runs for $3 \times 2$ cells. If you need to change the cells themselves, use indexed loops rather than an enhanced loop.

Source Materials
- AP Computer Science A Course and Exam Description
- AP Computer Science A Course and Exam Description Clarifications and Corrections
- AP Computer Science A Course Overview
- AP Computer Science A Course at a Glance
- AP Computer Science A Course at a Glance Poster
- Adopt AP Computer Science A
- AP Computer Science A
- AP Computer Science A