MOBI BOOT CAMP CORP. logoLearning Buddy
  • SIGN IN
  • Introduction
  • Unit 0: The First Program
  • Unit 1: Using Objects and Methods
  • Unit 2: Selection and Iteration
    • Part 1: Selection
    • Part 2: Iteration
      • while Loops
      • for Loops
      • Implementing Selection and Iteration Algorithms
      • Implementing String Algorithms
      • Nested Iteration
      • Informal Run-Time Analysis
      • Unit 2 Part 2 Slides
  • Unit 3: Class Creation
  • Unit 4: Data Collections

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.

Count-Controlled Iteration
  • for loops 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 Loop Header
  • The for loop 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:

  1. Initialization: A statement that runs once at the very beginning. It typically declares and initializes a loop control variable.
  2. Boolean Expression (Condition): An expression that is checked before each iteration. The loop continues as long as this is true.
  3. 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:

  1. Initialization: The loop control variable is initialized.
  2. Condition: The Boolean expression is evaluated. If false, the loop terminates.
  3. Body: If the condition is true, the code inside the loop executes.
  4. Update: The increment/decrement statement runs after the body has finished.
  5. Repeat: The program returns to step 2 to evaluate the condition again.
Generic For Loop Execution Flow
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);
		}
	}
}
For Loop Flowchart

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);
}
EXCLUSION STATEMENT
  • The break and continue statements, 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.

The break Keyword
  • break is an emergency exit. It stops the loop immediately and jumps to the code outside the loop block.
The continue Keyword
  • continue is 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
Privacy Policy | Terms & Conditions