Fiveable

💻AP Computer Science A Unit 2 Review

QR code for AP Computer Science A practice questions

2.8 For Loops

2.8 For Loops

Written by the Fiveable Content Team • Last updated June 2026
Verified for the 2027 exam
Verified for the 2027 examWritten by the Fiveable Content Team • Last updated June 2026
💻AP Computer Science A
Unit & Topic Study Guides

Frequently Asked Questions

Previous Exam Prep

Study Tools

Exam Skills

AP Cram Sessions 2021

Pep mascot

A for loop 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, 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 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 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 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 while loop and vice versa.
  • A loop control variable declared in the header is only in scope 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 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, 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, finish the inner loop 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 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 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. 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 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.

Vocabulary

The following words are mentioned explicitly in the College Board Course and Exam Description for this topic.

Term

Definition

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.

Frequently Asked Questions

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.

Pep mascot
Upgrade your Fiveable account to print any study guide

Download study guides as beautiful PDFs See example

Print or share PDFs with your students

Always prints our latest, updated content

Mark up and annotate as you study

Click below to go to billing portal → update your plan → choose Yearly→ and select "Fiveable Share Plan". Only pay the difference

Plan is open to all students, teachers, parents, etc
Pep mascot
Upgrade your Fiveable account to export vocabulary

Download study guides as beautiful PDFs See example

Print or share PDFs with your students

Always prints our latest, updated content

Mark up and annotate as you study

Plan is open to all students, teachers, parents, etc
report an error
description

screenshots help us find and fix the issue faster (optional)

add screenshot