Skip to main content
← AP CSA Study Guide

Code Scholars Tutoring · AP Computer Science A

3.1: For Loops

A for loop initializes once, checks its condition before each iteration, and updates after the body. Track the first included and first excluded value.

College Board Unit 2

How it works

A for loop packages initialization, a test condition, and an update into one header. The initialization runs once, the condition is checked before every iteration including the first, and the update runs after each body execution. A loop from 0 while i < n runs exactly n times. The enhanced for loop iterates over every element without an index and cannot be used to assign new values into an array.

Count iterations by listing the first and last values the counter actually takes, rather than subtracting the bounds.

Common error

Using less-than-or-equal against a length, which runs one pass too many and reads past the end.

Worked example

Java

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

Output

10

The four iterations add 1, 2, 3, and 4. The loop ends when i becomes 5.

Exercises

3.1.1 · Trace

Determine the exact output. Explain the Java rule or state changes that produce it.

Java

for (int i = 5; i > 0; i -= 2) {
    System.out.print(i + " ");
}
Show solution

Output

5 3 1 

The body runs for 5, 3, and 1; the next value -1 fails the condition.

3.1.2 · Write code

Write public static int sumEven(int n). Return the sum of even integers from 2 through n inclusive. Assume n is nonnegative.

Show solution

One valid solution is shown below. Other implementations satisfying the contract are also valid.

Java

public static int sumEven(int n) {
    int sum = 0;
    for (int i = 2; i <= n; i += 2) sum += i;
    return sum;
}

Check your code

Java

System.out.println(sumEven(0));
System.out.println(sumEven(7));
System.out.println(sumEven(8));

Expected output

0
12
20
Practice this topic: MCQ →

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic