Fiveable
Fiveable
AP Computer Science A
Find gaps with guided practice
Guided practice grid visualization
Table of Contents

💻ap computer science a review

4.2 For Loops

Verified for the 2025 AP Computer Science A examCitation:

The for loop is one of Java's most powerful and versatile iteration tools. While a while loop excels when the number of iterations is unknown, a for loop shines when you need to repeat code a specific number of times or iterate through collections of data. This study guide explores the structure, behavior, and applications of for loops, showing how they can make your code more efficient and readable when dealing with repetitive tasks.

For Loop Structure

The three components in the header serve specific purposes:

  1. Initialization: Sets up the initial state, typically by declaring and initializing a counter variable
  2. Conditional Expression: Determines whether the loop continues executing
  3. Incrementer: Updates the counter variable after each iteration

A for loop consists of three distinct parts enclosed in parentheses, followed by a block of code to be repeated:

for (initialization; conditional expression; incrementer) {
    // Code to be executed repeatedly (loop body)
}

For Loop Execution Flow

Understanding how a for loop executes is crucial:

  1. The initialization statement executes once at the beginning

  2. Before each iteration, the conditional expression is evaluated

    • If true, the loop body executes
    • If false, the loop terminates
  3. After executing the loop body, the incrementer runs

  4. The process repeats from step 2

This diagram illustrates the flow:

┌─────────────────┐
│  Initialization │
└────────┬────────┘
         │
         ▼
┌─────────────────┐     false
│   Conditional   │─────────→ (Exit Loop)
│    Expression   │
└────────┬────────┘
         │ true
         ▼
┌─────────────────┐
│    Loop Body    │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│   Incrementer   │
└────────┬────────┘
         │
         └─────────→

A Basic For Loop Example

Let's see a simple example that uses System.out.println to display numbers:

// Print numbers from 1 to 5
for (int i = 1; i <= 5; i++) {
    System.out.println("Number: " + i);
}

In this example:

  • int i = 1 initializes the counter
  • i <= 5 is the conditional expression that continues the loop while i is less than or equal to 5
  • i++ is the incrementer that adds 1 to i after each iteration

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

The Initialization Statement

The initialization statement executes only once before the loop begins. It typically:

  • Declares and initializes a loop control variable
  • Can declare multiple variables of the same type
  • Is separated by commas if initializing multiple variables
// Initialize a single variable
for (int i = 0; i < 10; i++) {
    // Loop body
}

// Initialize multiple variables
for (int i = 0, j = 10; i < j; i++, j--) {
    System.out.println("i = " + i + ", j = " + j);
}

Important notes:

  • Variables declared in the initialization are scoped to the loop
  • They cannot be accessed outside the loop
  • If you need to use the value after the loop, declare the variable before the loop

The Conditional Expression

The conditional expression is a boolean expression that:

  • Evaluates before each loop iteration
  • Continues the loop if it evaluates to true
  • Exits the loop if it evaluates to false
  • Can involve multiple conditions using logical operators
// Simple condition
for (int i = 0; i < 10; i++) {
    // Executes 10 times (i from 0 to 9)
}

// Complex condition
for (int i = 0; i < 100 && isPrime(i); i++) {
    // Executes until i reaches 100 or a non-prime number is found
}

The Incrementer

The incrementer executes after each iteration of the loop body. It typically:

  • Updates the loop control variable(s)
  • Can involve multiple statements separated by commas
  • Can use various forms of increment or decrement
// Standard increment
for (int i = 0; i < 10; i++) {
    // i increases by 1 each time
}

// Decrement
for (int i = 10; i > 0; i--) {
    // i decreases by 1 each time
}

// Custom step size
for (int i = 0; i < 100; i += 10) {
    // i increases by 10 each time (0, 10, 20, ...)
}

// Multiple updates
for (int i = 0, j = 10; i < j; i++, j--) {
    // i increases and j decreases each time
}

Common For Loop Patterns

Counting Up

for (int i = 1; i <= 10; i++) {
    System.out.println(i);
}
// Prints: 1 2 3 4 5 6 7 8 9 10

Counting Down

for (int i = 10; i >= 1; i--) {
    System.out.println(i);
}
// Prints: 10 9 8 7 6 5 4 3 2 1

Custom Increments

// Even numbers from 2 to 10
for (int i = 2; i <= 10; i += 2) {
    System.out.println(i);
}
// Prints: 2 4 6 8 10

Traversing Collections

One of the most common uses of for loops is to traverse (iterate through) collections of data.

Traversing Arrays

Arrays are fixed-size collections that store elements of the same type. A for loop can iterate through each element:

// Declare and initialize an array
int[] numbers = {5, 10, 15, 20, 25};

// Traverse the array using a for loop
for (int i = 0; i < numbers.length; i++) {
    System.out.println("Element at index " + i + ": " + numbers[i]);
}

Traversing ArrayLists

An ArrayList is a resizable collection from Java's Collections Framework. It can also be traversed with a for loop:

import java.util.ArrayList;

// Create and populate an ArrayList
ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");

// Traverse the ArrayList
for (int i = 0; i < names.size(); i++) {
    System.out.println("Name: " + names.get(i));
}

For Loop vs. While Loop

A while loop can always be rewritten as a for loop and vice versa. However, each has its strengths:

// While loop
int i = 0;
while (i < 10) {
    System.out.println(i);
    i++;
}

// Equivalent for loop
for (int i = 0; i < 10; i++) {
    System.out.println(i);
}

When to use each:

  • Use a for loop when the number of iterations is known in advance
  • Use a while loop when the number of iterations depends on a condition that might change during execution

Common Variations

Empty Components

Any of the three components in a for loop can be empty:

// Initialization outside the loop
int i = 0;
for (; i < 10; i++) {
    // Loop body
}

// Incrementer inside the loop body
for (int i = 0; i < 10;) {
    // Loop body
    i++;
}

// Condition checked inside (infinite loop with break)
for (int i = 0;;i++) {
    if (i >= 10) {
        break;
    }
    // Loop body
}

Enhanced For Loop (For-Each)

Java provides a simplified syntax for traversing collections called the "enhanced for loop" or "for-each loop":

int[] numbers = {5, 10, 15, 20, 25};

// Enhanced for loop
for (int number : numbers) {
    System.out.println(number);
}

This loop automatically iterates through each element without needing an explicit index.

Common For Loop Pitfalls

Off-by-One Errors

"Off-by-one" errors occur when loop iterations are one too many or one too few:

// Prints 0 to 9 (10 numbers)
for (int i = 0; i < 10; i++) {
    System.out.println(i);
}

// Prints 0 to 10 (11 numbers) - potential off-by-one error

for (int i = 0; i <= 10; i++) {
    System.out.println(i);
}

Infinite Loops

A for loop can become infinite if the conditional expression never evaluates to false:

// Infinite loop - i never changes

for (int i = 0; i < 10;) {
    System.out.println("This will print forever");
}

// Infinite loop - wrong direction

for (int i = 0; i < 10; i--) {
    System.out.println("i is now " + i);
}

Modifying Loop Variables Inside the Loop

Changing the loop variable inside the loop body can lead to unexpected behavior:

// Problematic: modifying i within the loop
for (int i = 0; i < 10; i++) {
    System.out.println("Starting iteration with i = " + i);
    
    // Don't do this!
    i = i + 2;
    
    System.out.println("Ending iteration with i = " + i);
}

Practical Examples

Example 1: Calculating Factorial

int number = 5;
int factorial = 1;

for (int i = 1; i <= number; i++) {
    factorial *= i;
}

System.out.println("Factorial of " + number + " is " + factorial);
// Output: Factorial of 5 is 120

Example 2: Finding Maximum Value in an Array

int[] values = {28, 15, 92, 47, 63, 8};
int max = values[0];  // Start with the first element

for (int i = 1; i < values.length; i++) {
    if (values[i] > max) {
        max = values[i];
    }
}

System.out.println("Maximum value: " + max);
// Output: Maximum value: 92

Example 3: Building a String Pattern

String pattern = "";
for (int i = 1; i <= 5; i++) {
    // Add i asterisks to the pattern
    for (int j = 0; j < i; j++) {
        pattern += "*";
    }
    pattern += "\n";  // Add a newline
}

System.out.println(pattern);
/*
Output:
*
**
***
****
*****
*/

Key Takeaways

  • For loops consist of three parts: initialization, conditional expression, and incrementer
  • The initialization runs once at the beginning of the loop
  • The conditional expression is evaluated before each iteration
  • The incrementer runs after each iteration of the loop body
  • For loops are ideal for traversing arrays and other collections
  • Any for loop can be rewritten as a while loop and vice versa
  • Watch out for off-by-one errors and infinite loops

In this section, we've explored the for loop, a powerful tool for controlled iteration in Java. For loops combine initialization, condition checking, and incrementing in a compact, readable format that clearly expresses the loop's intent and behavior. By mastering for loops, you'll be able to efficiently process data and perform repetitive tasks in your programs.

Key Terms to Review (8)

Arrays: Arrays are a collection of elements of the same data type, stored in contiguous memory locations. They have a fixed size and can be accessed using an index.
ArrayList: ArrayList is a dynamic data structure that allows you to store and manipulate collections of objects. Unlike arrays, ArrayLists can grow or shrink dynamically as needed.
Conditional Expression: A conditional expression is a statement that evaluates to either true or false based on the condition provided. It is commonly used in decision-making structures like if statements and loops.
For Loop: A for loop is a control flow statement that allows you to repeatedly execute a block of code for a specified number of times or until certain conditions are met.
Incrementer: An incrementer is an operator used to increase the value of a variable by one. It's commonly used in loops and counting scenarios.
System.out.println: System.out.println is a Java statement used to display output on the console. It prints the specified message or value and adds a new line character at the end.
Traverse: Traversing refers to the process of accessing each element in a data structure (such as arrays or linked lists) one by one, usually for performing some operation on them.
While loop: A while loop is a control flow statement that allows a block of code to be executed repeatedly as long as a specified condition is true.