0 / 8 页已完成

循环:forLoops: for

7.1 回顾 while 的计数循环7.1 Review: Counting with while

上一课我们学了用 while 做"重复 n 次"的循环:Last lesson we learned to use while for "repeat n times" loops:

C++
int i = 0;        // 1. 初始化
while (i < 5) {   // 2. 条件
    // 做事...
    i++;           // 3. 递增
}

每次写这种循环都要三步:初始化、条件、递增。有点啰嗦对吧?Every time you write this kind of loop, you need three steps: initialize, condition, increment. A bit verbose, right?

C++ 提供了一个快捷写法,把这三步压缩到一行 — 这就是 for 循环。C++ provides a shorthand that puts all three steps on one line — that's the for loop.

7.2 for 的语法7.2 for Syntax

C++
for (初始化; 条件; 递增) {
    // 条件成立时,反复执行
}

和 while 完全等价,只是把三个部分写在一行里:It's exactly the same as while, just with all three parts on one line:

部分Part 作用Purpose 执行时机When It Runs
int i = 0初始化计数器Initialize counter只在循环开始前执行一次Runs once before the loop starts
i < 5检查条件Check condition每次循环开始前检查Checked before each loop iteration
i++更新计数器Update counter每次循环结束后执行Runs after each loop iteration
for 和 while 的关系for vs. while

for 就是 while 的快捷写法。功能完全一样,只是更紧凑。当你知道"要重复几次"的时候,用 for 更方便。for is just shorthand for while. They do exactly the same thing, but for is more compact. When you know "how many times to repeat," for is more convenient.

7.3 最常见的模式:做 n 次7.3 Most Common Pattern: Do n Times

这是你以后写得最多的循环模式:This is the loop pattern you'll write most often:

C++
for (int i = 0; i < n; i++) {
    // 这里的代码会执行 n 次
    // i 的值依次是:0, 1, 2, ..., n-1
}

记住这个口诀:"从 0 开始,小于 n,做 n 次"Remember this rule: "Start at 0, less than n, do it n times."

7.4 实战:在屏幕上打印 1 到 107.4 Practice: Print 1 to 10 on Screen

C++ (VEXcode)
int main() {
    for (int i = 1; i <= 10; i++) {
        Brain.Screen.setCursor(i, 1);
        Brain.Screen.print("Number: %d", i);
    }

    return 0;
}
C++ (VS Code + VEX)
int main() {
    for (int i = 1; i <= 10; i++) {
        Brain.Screen.setCursor(i, 1);
        Brain.Screen.print("Number: %d", i);
    }

    return 0;
}
C++ (PROS)
void opcontrol() {
    for (int i = 1; i <= 10; i++) {
        pros::lcd::set_text(i, "Number: " + std::to_string(i));
    }
}

注意这里 i1 开始,条件是 <= 10,所以 i 的值是 1, 2, 3, ..., 10。Notice that i starts at 1 here with condition <= 10, so i takes values 1, 2, 3, ..., 10.

7.5 变量 i 的作用域7.5 Scope of Variable i

for 里面声明的变量 i只在循环内部有效A variable i declared inside for only exists inside the loop:

C++
for (int i = 0; i < 5; i++) {
    // 这里可以用 i
}
// 这里不能用 i!编译器会报错

这其实是个好事 — 循环结束了,计数器就自动"消失",不会干扰其他代码。This is actually a good thing — when the loop ends, the counter automatically "disappears" and won't interfere with other code.

如果你需要循环结束后还能用 i 的值,就把 i 声明在循环外面:If you need to use i's value after the loop ends, declare i outside the loop:

C++
int i;  // 声明在外面
for (i = 0; i < 5; i++) {
    // ...
}
// 这里 i 的值是 5

7.6 动手预测7.6 Predict the Output

C++
int total = 0;

for (int i = 2; i <= 6; i = i + 2) {
    total = total + i;
}
预测输出Predict the Output

循环结束后,total 等于多少?提示:注意递增部分是 i = i + 2,不是 i++After the loop, what does total equal? Hint: The increment is i = i + 2, not i++.

检查点Checkpoint
下面这个 for 循环,i 依次是哪些值?In the for loop below, what values does i take?
for (int i = 0; i < 4; i++) {
    // ...
}