---
title: "AP Computer Science A 2.8: For Loops"
description: "Review Java for loops for AP CSA, including the for loop header, initialization, Boolean condition, update statement, loop control variables, tracing, scope, and while-loop conversions."
canonical: "https://fiveable.me/ap-comp-sci-a/unit-2/for-loops/study-guide/DJuLxKz6SiSAX2cEVmCt"
type: "study-guide"
subject: "AP Computer Science A"
unit: "Unit 2 – Selection and Iteration"
lastUpdated: "2026-06-09"
---

# AP Computer Science A 2.8: For Loops

## Summary

Review Java for loops for AP CSA, including the for loop header, initialization, Boolean condition, update statement, loop control variables, tracing, scope, and while-loop conversions.

## Guide

A `for` [loop](/ap-comp-sci-a/key-terms/loop "fv-autolink") packs three pieces of loop control into one header: initialization, a Boolean condition, and an update. The initialization runs once, the condition is checked before every iteration, and the update runs after each pass through the loop body. For [AP Computer Science A](/ap-comp-sci-a "fv-autolink"), trace that exact order to predict how many times the loop runs and what each variable stores.

## Why This Matters for the AP Computer Science A Exam

`for` loops are one of the core iteration tools in AP Computer Science A, and [Unit 2](/ap-comp-sci-a/unit-2 "fv-autolink") carries a heavy weight on the exam. On multiple-choice questions, you will trace loops to find the final value of a variable, the output, or how many times a statement runs. You will also need to spot why a loop will not [compile](/ap-comp-sci-a/key-terms/compile "fv-autolink") or work as intended and fix it, which is a skill this topic builds directly.

On the free-response code-writing questions, you will write [methods](/ap-comp-sci-a/unit-3/abstraction-and-program-design/study-guide/o9VgVeIpKRYZ7N7rXfUz "fv-autolink") that use iteration to process values and call other methods. Knowing the exact order of initialization, condition check, body, and update lets you write loops that hit every value you intend without off-by-one mistakes.

## Key Takeaways

- A `for` loop header has three parts separated by semicolons: initialization, the Boolean condition, and the update.
- The initialization runs only once, before the first condition check. The variable it sets up is the loop control variable.
- The condition is checked before each iteration. If it is false at the start, the body never runs.
- The update runs after the loop body finishes each pass, then the condition is checked again.
- Any `for` loop can be rewritten as an [equivalent](/ap-comp-sci-a/unit-2/equivalent-boolean-expressions/study-guide/aMDnyFuOcAXnZigLW1vL "fv-autolink") `while` loop and vice versa.
- A loop control variable declared in the header is only in [scope](/ap-comp-sci-a/unit-3/scope-and-access/study-guide/56FUK4RSofr7slzwm6xm "fv-autolink") inside the loop.

## The Three-Part Header

Every `for` loop puts its control logic in one place at the top:

```java
for (initialization; condition; update) {
    // Loop body
}
```

- The **initialization** runs once before anything else.
- The **condition** is a Boolean expression checked before each iteration.
- The **update** runs after each pass through the body.

## How a for Loop Executes

The order of execution is what most questions test, so trace it carefully:

1. Run the initialization statement (only once).
2. Check the condition. If it is false, skip the entire loop.
3. If true, execute the loop body.
4. Run the update statement.
5. Go back to step 2.

The update happens after the body, not before. That single detail catches a lot of people on trace questions.

## Loop Control Variables and Scope

The variable set up in the initialization is your loop control variable. It decides when the loop stops. If you declare it inside the header, it only exists inside the loop.

```java
for (int i = 0; i < 5; i++) {
    System.out.println("i is: " + i);
}
// i is not accessible here - out of scope

```

If you need the value after the loop ends, declare the variable before the loop instead:

```java
int i;
for (i = 0; i < 10; i++) {
    // i is available here
}
System.out.println("Final i: " + i);  // Now i is accessible
```

## Converting Between for and while Loops

Any `for` loop can be rewritten as a `while` loop. Lining them up side by side shows where each control piece lives.

```java
// For loop version
for (int i = 1; i <= 10; i++) {
    System.out.println(i);
}

// Equivalent while loop
int i = 1;          // initialization
while (i <= 10) {   // condition
    System.out.println(i);
    i++;            // update
}
```

Being comfortable with both means you can switch loop types when one reads more clearly for the problem.

## Code Examples

### Basic Counting Patterns

```java
public class CountingExample {
    public static void main(String[] args) {
        // Count from 0 to 4
        for (int i = 0; i < 5; i++) {
            System.out.println("Iteration: " + i);
        }
        
        // Count from 1 to 5
        for (int count = 1; count <= 5; count++) {
            System.out.println("Count: " + count);
        }
        
        // Count backwards from 10 to 1
        for (int countdown = 10; countdown >= 1; countdown--) {
            System.out.println("T-minus " + countdown);
        }
    }
}
```

### Processing Arrays

[Arrays](/ap-comp-sci-a/unit-4/array-creation-and-access/study-guide/umTe6NA38OqZOhMZjFWi "fv-autolink") come later in the course, but seeing how a `for` loop walks through indexed values now will make those units easier.

```java
public class ArrayProcessing {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        
        // Print all elements
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Element " + i + ": " + numbers[i]);
        }
        
        // Calculate sum
        int sum = 0;
        for (int i = 0; i < numbers.length; i++) {
            sum += numbers[i];
        }
        System.out.println("Sum: " + sum);
        
        // Find maximum value
        int max = numbers[0];  // Start with first element
        for (int i = 1; i < numbers.length; i++) {  // Start from index 1
            if (numbers[i] > max) {
                max = numbers[i];
            }
        }
        System.out.println("Maximum: " + max);
    }
}
```

### Nested for Loops

```java
public class NestedLoopExample {
    public static void main(String[] args) {
        // Print a multiplication table
        System.out.println("Multiplication Table (1-5):");
        
        for (int row = 1; row <= 5; row++) {
            for (int col = 1; col <= 5; col++) {
                int product = row * col;
                System.out.print(product + "\t");  // Tab for spacing
            }
            System.out.println();  // New line after each row
        }
    }
}
```

### String Processing

```java
public class StringProcessing {
    public static void main(String[] args) {
        String word = "programming";
        
        // Print each character with its index
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            System.out.println("Index " + i + ": " + ch);
        }
        
        // Count vowels
        int vowelCount = 0;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                vowelCount++;
            }
        }
        System.out.println("Vowels found: " + vowelCount);
    }
}
```

### Step Patterns

```java
public class SkipPatterns {
    public static void main(String[] args) {
        // Print even numbers from 0 to 20
        for (int i = 0; i <= 20; i += 2) {
            System.out.print(i + " ");
        }
        System.out.println();
        
        // Print every third number
        for (int i = 3; i <= 30; i += 3) {
            System.out.print(i + " ");
        }
        System.out.println();
    }
}
```

You are not limited to `i++`. Using `i += 2` or `i -= 1` changes the step size and direction.

## How to Use This on the AP Computer Science A Exam

### Code Tracing

For multiple-choice [tracing](/ap-comp-sci-a/key-terms/tracing "fv-autolink"), write down the loop control variable at each iteration instead of doing it in your head. Track the condition check, the body output, and the update separately. The most common trap is forgetting the update runs after the body, so the last value the body sees is one step behind where you might guess.

For [nested loops](/ap-comp-sci-a/key-terms/nested-loops "fv-autolink"), finish the [inner loop](/ap-comp-sci-a/key-terms/inner-loop "fv-autolink") completely for every single pass of the outer loop before the outer loop advances. Trace the inner loop fully, then move the outer variable one step.

### Free Response

When you write methods that loop, decide your [bounds](/ap-comp-sci-a/key-terms/bounds "fv-autolink") first. To touch values at indices 0 through n minus 1, use `i < n`. Pick your starting value, your stopping condition, and your update so they agree with each other and with the range you actually need.

### Common Trap

When you need to terminate a loop early, that requires a conditional inside the body. If the statements are in the wrong order, the early exit can trigger too soon or never. Trace the order of statements carefully when early termination is involved.

## Practice Problems

### Problem 1: Sum of Squares

```java
public static int sumOfSquares(int n) {
    // Calculate 1^2 + 2^2 + 3^2 + ... + n^2
    // Your code here
}
```

**Solution**:
```java
public static int sumOfSquares(int n) {
    int sum = 0;
    for (int i = 1; i <= n; i++) {
        sum += i * i;  // Add i squared to sum
    }
    return sum;
}
```

`sumOfSquares(3)` returns `1 + 4 + 9 = 14`.

### Problem 2: Reverse String

```java
public static String reverseString(String str) {
    // Your code here - use a for loop

}
```

**Solution**:
```java
public static String reverseString(String str) {
    String reversed = "";
    for (int i = str.length() - 1; i >= 0; i--) {
        reversed += str.charAt(i);
    }
    return reversed;
}
```

Start from the last [index](/ap-comp-sci-a/key-terms/index "fv-autolink") and decrement back to the first.

### Problem 3: Find All Factors

```java
public static void printFactors(int number) {
    // Print all numbers that divide evenly into number
    // Your code here
}
```

**Solution**:
```java
public static void printFactors(int number) {
    System.out.println("Factors of " + number + ":");
    for (int i = 1; i <= number; i++) {
        if (number % i == 0) {  // i divides evenly into number
            System.out.print(i + " ");
        }
    }
    System.out.println();
}
```

`printFactors(12)` prints "1 2 3 4 6 12".

### Problem 4: Pattern Printing

```java
public static void printTriangle(int height) {
    // Print a triangle like:
    // *
    // **
    // ***
    // ****
}
```

**Solution**:
```java
public static void printTriangle(int height) {
    for (int row = 1; row <= height; row++) {
        for (int star = 1; star <= row; star++) {
            System.out.print("*");
        }
        System.out.println();  // New line after each row
    }
}
```

Use the outer loop for rows and the inner loop for the stars in each row.

## Common Misconceptions

- **The update runs before the body.** It does not. On each iteration, the body runs first, then the update, then the condition is checked again.
- **The initialization runs every time.** It runs only once, before the first condition check.
- **`i <= array.length` covers an array safely.** It runs one index too far and causes an [out-of-bounds error](/ap-comp-sci-a/key-terms/out-of-bounds-error "fv-autolink"). Use `i < array.length` to hit indices 0 through `length - 1`.
- **Updating in the wrong direction is harmless.** Using `i++` when you meant `i--` can create an [infinite loop](/ap-comp-sci-a/key-terms/infinite-loop "fv-autolink") because the variable never reaches the stopping condition.
- **A loop control variable declared in the header lives on after the loop.** It is out of scope once the loop ends. Declare it before the loop if you need it afterward.
- **`for` and `while` loops behave differently.** They are interchangeable. Any `for` loop can be rewritten as an equivalent `while` loop and vice versa.

## Related AP Computer Science A Guides

- [2.1 Algorithms with Selection and Repetition](/ap-comp-sci-a/unit-2/algorithms-with-selection-and-repetition/study-guide/42crNSZyW8IRsntk9IHe)
- [2.7 While Loops](/ap-comp-sci-a/unit-2/while-loops/study-guide/7qGsGOh1UKALAWpJhZOi)
- [2.6 Equivalent Boolean Expressions](/ap-comp-sci-a/unit-2/equivalent-boolean-expressions/study-guide/aMDnyFuOcAXnZigLW1vL)
- [2.11 Nested Iteration](/ap-comp-sci-a/unit-2/nested-iteration/study-guide/Buapg1KURHNbw6yRY8EZ)
- [2.12 Informal Code Analysis](/ap-comp-sci-a/unit-2/informal-code-analysis/study-guide/CR84MbOE4FDDoSVokDVZ)
- [2.10 Developing Algorithms Using Strings](/ap-comp-sci-a/unit-2/developing-algorithms-using-strings/study-guide/hDOL1VhnMQFPkBf6xMMW)

## Vocabulary

- **Boolean expression**: An expression that evaluates to either true or false, used to control the execution of loops and conditional statements.
- **for loop**: A type of iterative statement that repeats a block of code a specified number of times using initialization, a Boolean expression, and an update statement.
- **initialization**: The first assignment of a value to a variable.
- **iteration statement**: A control structure that repeats a block of code multiple times based on a condition.
- **loop body**: The segment of code that is repeated within an iteration statement.
- **loop control variable**: The variable initialized in a for loop that is used to control the number of iterations.
- **update**: The part of a for loop header that modifies the loop control variable after each iteration of the loop body.
- **while loop**: An iterative statement that repeatedly executes a block of code as long as a specified Boolean expression evaluates to true.

## FAQs

### What is a for loop in Java?

A for loop is a repetition structure that usually puts initialization, a Boolean condition, and an update statement in one header so a block of code can run multiple times.

### How many statements are included in a for loop header?

A standard Java for loop header has three parts separated by semicolons: initialization, condition, and update. The loop body is separate from the header.

### What order does a for loop run in?

The initialization runs once, then the condition is checked. If true, the body runs, then the update runs, and the condition is checked again.

### What is a loop control variable?

A loop control variable is the variable that tracks loop progress, such as i in for (int i = 0; i < n; i++). It helps determine when the loop stops.

### Can every for loop be written as a while loop?

Yes. A for loop can be rewritten as a while loop by moving the initialization before the loop, keeping the condition in the while header, and placing the update at the end of the loop body.

### How are for loops tested on the AP CSA exam?

You may trace output, count iterations, identify off-by-one errors, convert between for and while loops, or write methods that use for loops to process numbers, Strings, or arrays.

## Structured Data

```json
{"@context":"https://schema.org","@type":"FAQPage","inLanguage":"en","mainEntity":[{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2/for-loops/study-guide/DJuLxKz6SiSAX2cEVmCt#what-is-a-for-loop-in-java","name":"What is a for loop in Java?","acceptedAnswer":{"@type":"Answer","text":"A for loop is a repetition structure that usually puts initialization, a Boolean condition, and an update statement in one header so a block of code can run multiple times."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2/for-loops/study-guide/DJuLxKz6SiSAX2cEVmCt#how-many-statements-are-included-in-a-for-loop-header","name":"How many statements are included in a for loop header?","acceptedAnswer":{"@type":"Answer","text":"A standard Java for loop header has three parts separated by semicolons: initialization, condition, and update. The loop body is separate from the header."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2/for-loops/study-guide/DJuLxKz6SiSAX2cEVmCt#what-order-does-a-for-loop-run-in","name":"What order does a for loop run in?","acceptedAnswer":{"@type":"Answer","text":"The initialization runs once, then the condition is checked. If true, the body runs, then the update runs, and the condition is checked again."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2/for-loops/study-guide/DJuLxKz6SiSAX2cEVmCt#what-is-a-loop-control-variable","name":"What is a loop control variable?","acceptedAnswer":{"@type":"Answer","text":"A loop control variable is the variable that tracks loop progress, such as i in for (int i = 0; i < n; i++). It helps determine when the loop stops."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2/for-loops/study-guide/DJuLxKz6SiSAX2cEVmCt#can-every-for-loop-be-written-as-a-while-loop","name":"Can every for loop be written as a while loop?","acceptedAnswer":{"@type":"Answer","text":"Yes. A for loop can be rewritten as a while loop by moving the initialization before the loop, keeping the condition in the while header, and placing the update at the end of the loop body."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-2/for-loops/study-guide/DJuLxKz6SiSAX2cEVmCt#how-are-for-loops-tested-on-the-ap-csa-exam","name":"How are for loops tested on the AP CSA exam?","acceptedAnswer":{"@type":"Answer","text":"You may trace output, count iterations, identify off-by-one errors, convert between for and while loops, or write methods that use for loops to process numbers, Strings, or arrays."}}]}
```
