Mr.Mou @ ShiShi AP Center

AP CSA 2.8:for 循环

A while loop separates initialization, testing, and updating into different places. A for loop places those three parts together in one header, making counter-controlled repetition easier to read.

while 循环把初始化、条件检查和变量更新写在不同位置,而 for 循环会把这三个部分集中写在循环头中,更适合控制明确次数的重复。

A for loop initializes once, checks the condition before every iteration, and updates after every completed loop body. for 循环只初始化一次;每次迭代前检查条件;每次循环体执行完后更新变量。

Core Concepts:
核心知识点

1. Trace the Values Generated by the Header
追踪循环头产生的数值

What is printed?

下面的代码会输出什么?

int result = 1;

for (int i = 3; i < 6; i += 2)
{
    result *= i;
}

System.out.println(result);

Answer:

15

The loop variable takes these values:

循环变量会依次取下面的值:

i = 3
i = 5

Trace the loop:

逐次追踪:

Stage i Condition result
Start
开始
3 3 < 6true 1
After iteration 1
第 1 次迭代后
5 Update completed
完成更新
3
Before iteration 2
第 2 次迭代前
5 5 < 6true 3
After iteration 2
第 2 次迭代后
7 Update completed
完成更新
15
Final check
最后检查
7 7 < 6false 15

The update i += 2 runs after the loop body. Therefore, the body uses i = 3 and i = 5.

更新语句 i += 2 会在循环体执行后运行。因此,循环体中使用的值是 35

2. The Three Parts of a for Loop
for 循环的三个部分

The general form is:

基本结构如下:

for (initialization; booleanExpression; update)
{
    statements;
}

Example:

for (int count = 1; count <= 5; count++)
{
    System.out.println(count);
}
1
2
3
4
5

The header contains three parts:

循环头包含三个部分:

Part Example Purpose
Initialization
初始化
int count = 1 Creates the loop variable and gives it a starting value.
创建循环变量并设置初始值。
Boolean expression
布尔表达式
count <= 5 Decides whether the next iteration runs.
决定是否执行下一次迭代。
Update
更新
count++ Changes the loop variable after each iteration.
每次迭代后改变循环变量。

The two semicolons in the header are required:

循环头中的两个分号是必需的:

for (initialization; condition; update)

Do not replace them with commas.

不能使用逗号代替这两个分号。

3. Execution Order of a for Loop
for 循环的执行顺序

Consider:

观察下面的代码:

for (int i = 2; i <= 6; i += 2)
{
    System.out.print(i + " ");
}
2 4 6

Java follows this order:

Java 会按照下面的顺序执行:

  1. Run the initialization once. 初始化只执行一次。

    int i = 2;
    
  2. Check the condition. 检查条件。

    i <= 6
    
  3. If the condition is true, run the entire loop body. 如果条件为真,执行完整的循环体。

  4. Run the update. 执行更新语句。

    i += 2;
    
  5. Return to the condition. 返回循环条件,再次检查。

  6. Stop when the condition becomes false. 当条件变为假时,退出循环。

The important order is:

最重要的执行顺序是:

initialize → test → body → update → test → body → update

The update does not run before the first iteration.

第一次迭代前不会执行更新语句。

4. Common Counting Patterns
常见计数模式

Count from 0 up to, but not including, n
0 数到 n - 1

for (int i = 0; i < n; i++)
{
    statements;
}

When n is positive, this loop runs n times.

n 为正数时,这个循环会执行 n 次。

For n = 5, the values are:

n = 5 时:

0 1 2 3 4

Count from 1 through n
1 数到 n

for (int i = 1; i <= n; i++)
{
    statements;
}

For n = 5, the values are:

n = 5 时:

1 2 3 4 5

This loop also runs five times.

这个循环同样执行五次。

Header pattern Values when n = 5 Iterations
int i = 0; i < n; i++ 0, 1, 2, 3, 4 5
int i = 1; i <= n; i++ 1, 2, 3, 4, 5 5

Do not decide the number of iterations by looking only at the ending value. Check the starting value, condition, and update together.

不能只看结束值来判断循环次数。必须同时检查初始值、条件和更新方式。

5. Counting Backward and Skipping Values
反向计数与跳跃计数

The update does not have to be i++.

更新语句不一定是 i++

Counting backward
反向计数

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

All three parts support the backward direction:

三个部分都与反向计数保持一致:

Counting by twos
每次增加 2

for (int i = 0; i <= 10; i += 2)
{
    System.out.print(i + " ");
}
0 2 4 6 8 10

Counting backward by twos
每次减少 2

for (int i = 5; i >= 1; i -= 2)
{
    System.out.print(i + " ");
}
5 3 1

When counting backward, the condition and update must both point toward smaller values.

反向计数时,循环条件和更新方式都必须与数值减小的方向一致。

6. Equivalent for and while Loops
等价的 forwhile 循环

A for loop can be rewritten as a while loop.

for 循环可以改写成等价的 while 循环。

for version
for 版本

for (int i = 3; i > 0; i--)
{
    System.out.println(i);
}

Equivalent while version
等价的 while 版本

int i = 3;

while (i > 0)
{
    System.out.println(i);
    i--;
}

Both versions print:

两个版本都会输出:

3
2
1

The parts map directly:

各部分的对应关系如下:

for loop part Location in the while loop
Initialization
初始化
Before the while loop
写在 while 前面
Boolean expression
布尔表达式
In the while header
写在 while 循环头中
Update
更新
At the end of the loop body
写在循环体末尾

When comparing two loops on an AP question, check whether they generate the same loop-variable values in the same order.

在 AP 题目中比较两个循环时,应检查它们是否按照相同顺序产生相同的循环变量值。

7. Boundary Values and Iteration Counts
边界值与迭代次数

How many times does this loop print "*"?

下面的循环会输出多少个 "*"

for (int i = 3; i <= 9; i++)
{
    System.out.print("*");
}

Answer: Seven times.

答案:七次。

The values are:

循环变量的值为:

3 4 5 6 7 8 9

Count the actual values rather than subtracting carelessly.

应该数出循环变量实际取到的值,而不是直接进行不完整的减法。

For a loop that increases by 1 and includes both endpoints:

对于每次增加 1,并且包含起点与终点的循环:

number of iterations = ending value - starting value + 1

Here:

这里:

9 - 3 + 1 = 7

Compare:

比较:

Loop header Values Iterations
int i = 3; i < 9; i++ 3, 4, 5, 6, 7, 8 6
int i = 3; i <= 9; i++ 3, 4, 5, 6, 7, 8, 9 7

Changing < to <= often adds one iteration.

< 改成 <=,通常会增加一次迭代。

8. Changing the Header Changes the Result
改变循环头会改变结果

Compare these loops.

比较下面两个循环。

Original loop

int result = 1;

for (int i = 3; i < 6; i += 2)
{
    result *= i;
}

System.out.println(result);

The values of i are:

i 的值为:

3 5

The output is:

输出为:

15

Changed loop

int result = 1;

for (int i = 4; i <= 6; i += 2)
{
    result *= i;
}

System.out.println(result);

The values of i are:

i 的值为:

4 6

The output is:

输出为:

24

Both loops execute twice, but they use different values. Therefore, their outputs are different.

两个循环都执行两次,但使用的循环变量值不同,因此输出不同。

On AP questions, distinguish between:

做 AP 题时,需要区分:

Two loops can have the same number of iterations but produce different results.

两个循环可能执行相同次数,却产生不同结果。

9. Common Beginner Mistakes
常见初学者错误

Mistake Why it is wrong Correct understanding
Thinking the update runs before the body.
认为更新语句先于循环体执行。
The current value is used by the body before the update.
循环体先使用当前值,之后才更新。
Follow: test → body → update.
按照“检查、循环体、更新”的顺序执行。
Using < when the final value must be included.
需要包含结束值时使用 <
The loop stops before reaching that value.
循环会在达到结束值前停止。
Use <= when the boundary should be included.
需要包含边界时使用 <=
Counting only the distance between endpoints.
只计算起点与终点之间的差。
An inclusive loop contains both endpoints.
包含边界的循环会同时使用起点和终点。
List the values or add 1 when appropriate.
列出实际值,或在适用时加 1
Increasing while testing for smaller values.
条件要求变小,但变量却不断增加。
The condition may remain true forever.
条件可能永远为真。
Match the update direction to the stopping condition.
让更新方向与停止条件保持一致。
Forgetting both semicolons in the header.
忘记循环头中的两个分号。
The for header will not compile.
循环头无法通过编译。
Use for (initialization; condition; update).
三个部分之间使用两个分号。
Assuming equal iteration counts mean equal output.
认为循环次数相同,输出就一定相同。
The loops may use different variable values.
循环可能使用不同的变量值。
Trace the exact values used by the body.
追踪循环体实际使用的每一个值。

10. Debugging Example
调试例子

The following loop is supposed to print:

下面的循环原本应该输出:

5 3 1

Buggy code:

错误代码:

for (int count = 1; count <= 5; count++)
{
    System.out.print(count + " ");
}

Actual output:

实际输出:

1 2 3 4 5

The loop runs, but its logic does not match the required pattern. This is a logic error.

循环能够运行,但逻辑与目标不符。这属于逻辑错误

Three parts must change:

三个部分都需要修改:

  1. Start at 5, not 1. 从 5 开始,而不是 1

  2. Continue while the value is at least 1. 当数值仍然大于或等于 1 时继续。

  3. Decrease by 2. 每次减少 2

Fixed code

for (int count = 5; count >= 1; count -= 2)
{
    System.out.print(count + " ");
}
5 3 1
Problem Effect Fix
Starts at 1 Begins at the wrong endpoint.
从错误的端点开始。
Initialize count to 5.
Uses count <= 5 Describes an increasing range.
描述的是递增范围。
Use count >= 1.
Uses count++ Moves upward instead of downward by two.
向上增加,而不是每次减少二。
Use count -= 2.

11. Mini Practice
小练习

Practice 1: Predict the Output
练习一:预测输出

What is printed?

下面的代码会输出什么?

for (int i = 3; i < 8; i++)
{
    System.out.print(i + " ");
}

Answer:

3 4 5 6 7

The value 8 is not included because the condition is i < 8.

因为条件是 i < 8,所以不会包含 8


Practice 2: Determine the Iteration Count
练习二:判断迭代次数

How many times does the loop body run?

循环体会执行多少次?

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

Answer: Five times.

答案:五次。

2 4 6 8 10

Practice 3: Predict the Final Value
练习三:预测最终值

What is printed?

下面的代码会输出什么?

int sum = 0;

for (int i = 1; i <= 5; i += 2)
{
    sum += i;
}

System.out.println(sum);

Answer:

9

The loop adds:

循环会相加:

1 + 3 + 5 = 9

Practice 4: Match the while Loop
练习四:匹配 while 循环

Which while loop is equivalent to this for loop?

下面哪个 while 循环与这段 for 循环等价?

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

A.

int i = 1;

while (i <= 4)
{
    i++;
    System.out.print(i);
}

B.

int i = 1;

while (i <= 4)
{
    System.out.print(i);
    i++;
}

C.

int i = 0;

while (i <= 4)
{
    System.out.print(i);
    i++;
}

Answer: B

The body uses the current value before the update, exactly like the for loop.

循环体先使用当前值,再执行更新,与原来的 for 循环一致。


Practice 5: Find the Infinite Loop
练习五:找出无限循环

What is wrong with this loop?

下面的循环有什么问题?

for (int i = 0; i < 5; i--)
{
    System.out.println(i);
}

Answer: The update moves i in the wrong direction.

答案:更新语句让 i 朝错误的方向变化。

The values become:

变量值会变成:

0 -1 -2 -3 ...

The condition i < 5 remains true, so the loop does not stop.

条件 i < 5 会始终为真,因此循环不会停止。

A possible fix is:

一种修复方式是:

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

Quick Checklist
快速检查清单

Before answering a Topic 2.8 question, check:

做 2.8 的题目之前,检查: