PrepGo

for Loops - AP Computer Science A Study Guide

Written by AP Content Team, Verified for 2026 AP Exams, Last updated: May 2026

Learn with study guides reviewed by top AP teachers. This guide takes about 10 minutes to read.

Getting Started

In programming, we often need to repeat a block of code a specific number of times. For example, you might need to print a student's name 10 times, calculate the sum of the first 100 integers, or process every character in a word. A for loop is a fundamental control structure in Java designed for this exact purpose: performing a task for a predetermined number of repetitions.

What You Should Be Able to Do

  • Write a for loop to execute a block of code a specified number of times.

  • Identify the three key components of a for loop header: initialization, condition, and increment.

  • Trace the execution of a for loop, tracking the value of its control variable through each iteration.

  • Recognize and correct common for loop errors, especially "off-by-one" errors.

Key Concepts & Java Implementation

The Core Idea

A for loop is a structure for definite iteration, meaning the loop is executed a known number of times. It automates the process of counting. Imagine you have a counter variable; the for loop provides a compact syntax to:

  1. Set the counter to a starting value.

  2. Check if the counter has reached its ending value.

  3. Execute your code if it hasn't.

  4. Increase (or decrease) the counter.

  5. Repeat from step 2.

This entire mechanism is managed within a single line of code called the loop header, making your code cleaner and less error-prone than managing the counter manually.

Syntax & Implementation

The for loop is defined by a header and a body. The header contains three parts, separated by semicolons, that control the loop's execution.

  • Syntax Table
ComponentPurposeJava Example
InitializationA statement that runs only once at the very beginning. It typically declares and initializes a loop control variable.int i = 0
ConditionA boolean expression that is checked before each iteration. The loop body executes only if this expression is true.i < 10
Increment/UpdateA statement that runs after each iteration. It is typically used to modify the loop control variable to progress toward the end condition.i++
Loop BodyThe block of code enclosed in curly braces {...} that is repeated as long as the condition is true.{ System.out.println(i); }
  • Annotated Java Examples

Example 1: A Standard Counting Loop

This loop prints the numbers from 0 to 4. It runs exactly 5 times.


// The for loop header controls the iteration

for (int i = 0; i < 5; i++) {

    // This is the loop body. It executes on each iteration.

    System.out.println("The current value of i is: " + i);

}

System.out.println("Loop finished.");

Output:


The current value of i is: 0

The current value of i is: 1

The current value of i is: 2

The current value of i is: 3

The current value of i is: 4

Loop finished.

Example 2: A Loop That Counts Down

The increment/update part can also decrement the loop variable.


// This loop counts down from 3 to 1

for (int count = 3; count > 0; count--) {

    System.out.println(count);

}

System.out.println("Blast off!");

Output:


3

2

1

Blast off!

Tracing & Analysis

  • Execution Trace

To fully understand a loop, you must trace its execution. Let's trace the first example: for (int i = 0; i < 5; i++).

IterationActioni Value (at start)Condition Check (i < 5)ResultBody Executes?i Value (after i++)
-Initialization0----
1Condition Check00 < 5trueYes (prints 0)1
2Condition Check11 < 5trueYes (prints 1)2
3Condition Check22 < 5trueYes (prints 2)3
4Condition Check33 < 5trueYes (prints 3)4
5Condition Check44 < 5trueYes (prints 4)5
6Condition Check55 < 5falseNoLoop terminates
  • Analysis

The most common logic error with loops is the off-by-one error, where the loop runs one too many or one too few times. This is almost always caused by an incorrect condition.

  • To run a loop N times starting from 0, the condition should be i < N.

  • To run a loop N times starting from 1, the condition should be i <= N.

Additionally, it is considered poor practice to modify the loop control variable (i in our examples) inside the loop body. The header is designed to manage this variable, and manual changes can lead to unexpected behavior like infinite loops or skipping iterations.

Java Syntax Quick-Reference

A compact reference for the syntax introduced in this topic.

  • for (initialization; condition; increment) { ... }: A control structure for definite iteration. It executes its body as long as the condition remains true.

  • ++ (Increment Operator): A unary operator that increases a numeric variable's value by one. i++ is shorthand for i = i + 1.

  • -- (Decrement Operator): A unary operator that decreases a numeric variable's value by one. i-- is shorthand for i = i - 1.

  • <= (Less Than or Equal To): A relational operator that returns true if the left operand is less than or equal to the right operand.

  • >= (Greater Than or Equal To): A relational operator that returns true if the left operand is greater than or equal to the right operand.

Core Code Examples & Terminology

  • Iteration: The process of repeating a set of instructions. A single execution of a loop's body is called one iteration.

  • Loop Control Variable: A variable whose value is used to control the flow of a loop. It is typically initialized before the loop starts and updated after each iteration.

  • Initialization Statement: The first part of a for loop header. It executes only once to set up the loop control variable.

  • Condition (Boolean Expression): The second part of a for loop header. It is evaluated before each iteration; the loop continues only if the expression is true.

  • Increment/Update Statement: The third part of a for loop header. It is executed at the end of each iteration to modify the loop control variable.

  • Off-by-One Error: A logic error where a loop executes one time too many or one time too few. This is often caused by using < instead of <= or starting/ending the loop at the wrong value.

  • Core Snippet 1 (Standard for loop):

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

    This loop executes its body exactly 10 times, with i taking on values from 0 to 9.

  • Core Snippet 2 (Summation Loop):

    
    int total = 0;
    
    for (int num = 1; num <= 5; num++) {
    
        total = total + num;
    
    }
    

    This loop calculates the sum of integers from 1 to 5 (1 + 2 + 3 + 4 + 5), resulting in total being 15.

Core Skill Check

  • Code Tracing: What is the final value of x after this Java code runs: int x = 10; for (int i = 0; i < 4; i++) { x = x - 2; }?

  • Debugging: Identify the error in this Java code that causes an infinite loop: for (int n = 1; n > 0; n++) { System.out.println(n); }.

  • Application: Write a single line of Java code for a for loop header that will cause its body to execute 50 times, starting a counter variable c at 1.

Common Misconceptions & Errors

  1. Off-by-One Errors: The most frequent bug. To loop N times, a loop from int i = 0 must have the condition i < N, not i <= N. Double-check your boundary conditions.

  2. Semicolon after Header: Placing a semicolon after the for loop's header, like for (int i = 0; i < 5; i++);, creates a loop with an empty body. The loop will run 5 times doing nothing, and the code block you intended to be the body will execute only once afterward.

  3. Modifying the Loop Variable in the Body: Changing the loop control variable (e.g., i) inside the loop body is dangerous. It disrupts the predictable control flow managed by the header and can cause infinite loops or other logical errors.

  4. Incorrect Update: Using an increment (i++) when you need a decrement (i--), or vice-versa, can prevent the loop's condition from ever becoming false, resulting in an infinite loop.

Summary

The for loop is Java's primary tool for definite iteration, allowing you to execute a block of code a known number of times. Its power lies in its compact header, which combines initialization, a continuation condition, and an update statement into a single, readable line. This structure automates the counting process, making code for repetitive tasks cleaner and more reliable. Mastering the for loop requires understanding how these three parts work together and being vigilant against common pitfalls like off-by-one errors.