如果循环次数比较明确,for 循环通常比 while 更清晰。它把“依次取出一组值”这件事写在一行里。
for 的计数结构
C++ 的计数循环把初始化、继续条件和更新语句写在同一对括号中。
for (int i = 0; i < 5; i++) {
cout << i << " " << endl;
}
cout << endl;
for (int i = 1; i < 10; i += 2) {
cout << i << " " << endl;
}运行结果:
0 1 2 3 4
10 11 12 13 14
1 3 5 7 9for (初始化; 条件; 更新) 先执行初始化;每轮开始前检查条件;每轮结束后执行更新。
知识测验
题目
for (int i = 0; i < 5; i++) 会生成哪些整数?
固定次数的累加
计算 1 到 100 的整数和,可以使用 for (int i = 1; i <= 100; i++)。条件使用 i <= 100,因此 100 会被包含。
int total = 0;
for (int i = 1; i <= 100; i++) {
total += i;
}
cout << total << endl;运行结果:
1 到 100 的总和:5050这种写法比 while 更容易看出循环变量 i 的取值范围。
互动实验
逐行跟踪求和循环
访问权限免费
逐语句运行代码,观察 i 如何流入 total。
C++● DEBUG
01int total = 0;02for (int i = 1; i <= 100; i++) {03 total += i;04}05cout << total << endl;
i—
total0
进度0/100
CONSOLE
>>>
知识测验
题目
要让 i 依次取 1 到 100,应该使用哪个 for 循环头?
斐波那契数列
斐波那契数列(Fibonacci sequence)的前两项是 1, 1,从第三项开始,每一项都等于前两项之和。
int n = 10;
int first = 1;
int second = 1;
cout << first << " " << second << " " << endl;
for (int i = 3; i <= n; i++) {
int current = first + second;
cout << current << " " << endl;
first = second;
second = current;
}一次可能的运行结果:
请输入项数:10
1 1 2 3 5 8 13 21 34 55循环中最重要的更新是这两行:
int first = 1;
int second = 1;
int current = first + second;
first = second;
second = current;它们会把窗口向后移动一格,让下一轮继续使用“前两项”。
互动实验
滑动斐波那契窗口
访问权限免费
每次点击只执行下一条赋值语句;注意两次赋值的先后顺序。
C++● DEBUG
01int first = 1, second = 1;02for (int i = 3; i <= 10; i++) {03 int current = first + second;04 first = second;05 second = current; }
first1
second1
current—
i—
first1second1
知识测验
题目
斐波那契循环中,first = second; second = current 的作用是什么?
动手练习
列出区间内的闰年
输入起始年份和结束年份,使用 for 循环找出区间内的所有闰年。
- 读取 start_year 和 end_year。
- 遍历闭区间内的每一年并判断是否为闰年。
- 把所有闰年输出到同一行。