Unit 2.8: for Loops
A for loop is a type of iterative statement that is ideal when you know exactly how many times you want the loop to run.
forloops consolidate management of the loop control variable. They are most effective when the number of iterations is known before the loop begins.
While it performs the same function as a while loop, it is often preferred because it consolidates the three essential components of iteration—initialization, condition, and update—into a single, readable line.
The for Loop Header
As discussed in Unit 2.7, every loop needs three parts to manage its execution.
- The
forloop header contains the initialization, condition, and update all in one place. This makes the loop's structure explicit and easy to read.
In a for loop, these are placed together in the header, separated by semicolons:
- Initialization: A statement that runs once at the very beginning. It typically declares and initializes a loop control variable.
- Boolean Expression (Condition): An expression that is checked before each iteration. The loop continues as long as this is
true. - Update: A statement that is executed at the end of each iteration. It typically increments or decrements the loop control variable.
Syntax:
for (initialization; boolean_expression; update) {
// statements to execute
}
Execution Order and the Loop Control Variable
In a for loop, the initialization statement is executed only once before the first evaluation of the Boolean expression. The variable being initialized (e.g., int i = 0) is formally referred to as the loop control variable.
The execution proceeds in this specific order:
- Initialization: The loop control variable is initialized.
- Condition: The Boolean expression is evaluated. If
false, the loop terminates. - Body: If the condition is
true, the code inside the loop executes. - Update: The increment/decrement statement runs after the body has finished.
- Repeat: The program returns to step 2 to evaluate the condition again.
public class ForLoopDemo {
public static void main(String args[]) {
// This loop will print numbers from 10 up to 14
for (int x = 10; x < 15; x++) {
System.out.println("Value of x: " + x);
}
}
}
Equivalence to a while Loop
A for loop can be rewritten into an equivalent while loop (and vice versa). This helps to understand how the three parts of the for header map to the structure of a while loop.
Example: for loop to while loop
Task: Converting a for loop into an equivalent while loop.
// For Loop
for (int i = 0; i < 3; i++) {
System.out.println("Loop: " + i);
}
// Equivalent While Loop
int i = 0; // 1. Initialization
while (i < 3) { // 2. Condition
System.out.println("Loop: " + i);
i++; // 3. Update
}
Example: while loop to for loop
Task: Converting a while loop into an equivalent for loop.
// While Loop
int k = 5;
while (k > 0) {
System.out.println(k);
k--;
}
// Equivalent For Loop
for (int k = 5; k > 0; k--) {
System.out.println(k);
}
Iterating with Arrays
for loops are the most common way to process all elements in an array. You can do this using either a standard indexed for loop or an enhanced for loop (also called a for-each loop).
Example: Standard Indexed for Loop
This version uses an index variable (i) to access each element. It is useful if you need to know the position of the element or if you want to modify the array.
Task: Using an indexed for loop to traverse an array.
int[] grades = {85, 92, 78};
for (int i = 0; i < grades.length; i++) {
System.out.println("Grade at index " + i + ": " + grades[i]);
}
Example: Enhanced for Loop
This version is simpler and less error-prone if you only need to read the values. It automatically "hands you" each element one by one.
Task: Using an enhanced for loop to traverse an array.
int[] grades = {85, 92, 78};
for (int score : grades) {
System.out.println("Grade: " + score);
}
- The
breakandcontinuestatements, which can be used to alter the flow of a loop, are not part of the AP Computer Science A course and will not be on the AP Exam. However, understanding them is useful for general programming.
Break and Continue
The break and continue keywords provide additional control over loop execution.
breakis an emergency exit. It stops the loop immediately and jumps to the code outside the loop block.
continueis a skip button. It stops the current iteration and jumps immediately to the next update/condition check.
Example: Using break
Task: Breaking out of a loop early.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
System.out.print(i + " ");
}
// Output: 0 1 2 3 4
Example: Using continue
Task: Skipping an iteration using continue.
for (int i = 0; i < 5; i++) {
if (i == 2) {
continue; // Skip printing for 2, proceed to i++
}
System.out.print(i + " ");
}
// Output: 0 1 3 4