在本教程中,我们将在一些示例的帮助下了解 C++ for循环及其工作原理。
在计算机编程中,循环用于重复代码块。
例如,假设我们要显示一条消息 100 次。 然后,我们可以使用循环来代替写print语句 100 次。
那只是一个简单的例子; 通过有效地使用循环,我们可以在程序中实现更高的效率和复杂性。
C++ 中有 3 种循环类型。
for循环while循环do...while循环
本教程重点介绍 C++ for循环。 我们将在以后的教程中学习其他类型的循环。
C++ for循环
for循环的语法为:
for (initialization; condition; update) {// body of-loop}
这里,
initialization- 初始化变量,仅执行一次condition- 如果执行true,则执行for循环的主体
如果执行false,则终止for循环update- 更新初始化变量的值,然后再次检查条件
要了解有关conditions的更多信息,请查看我们的 C++ 关系和逻辑运算符教程。
C++ 中for循环的流程图

C++ 中for循环的流程图
示例 1:从 1 到 5 打印数字
#include <iostream>using namespace std;int main() {for (int i = 1; i <= 5; ++i) {cout << i << " ";}return 0;}
输出
1 2 3 4 5
该程序的工作原理如下
| 迭代 | 变量 | i <= 5 |
行为 |
|---|---|---|---|
| 1 | i = 1 |
true |
1 被打印。i增加到2。 |
| 2 | i = 2 |
true |
2 被打印。i增加到3。 |
| 3 | i = 3 |
true |
3 被打印。i增加到4。 |
| 4 | i = 4 |
true |
4 被打印。i增加到5。 |
| 5 | i = 5 |
true |
5 被打印。i增加到6。 |
| 6 | i = 6 |
false |
循环终止 |
示例 2:显示文本 5 次
// C++ Program to display a text 5 times#include <iostream>using namespace std;int main() {for (int i = 1; i <= 5; ++i) {cout << "Hello World! " << endl;}return 0;}
输出
Hello World!Hello World!Hello World!Hello World!Hello World!
该程序的工作原理如下
| 迭代 | 变量 | i <= 5 |
行为 |
|---|---|---|---|
| 1 | i = 1 |
true |
打印Hello World!并将i增加到2。 |
| 2 | i = 2 |
true |
打印Hello World!并将i增加到3。 |
| 3 | i = 3 |
true |
打印Hello World!并将i增加到4。 |
| 4 | i = 4 |
true |
打印Hello World!并将i增加到5。 |
| 5 | i = 5 |
true |
打印Hello World!并将i增加到6。 |
| 6 | i = 6 |
false |
循环终止 |
示例 3:查找前 n 个自然数的总和
// C++ program to find the sum of first n natural numbers// positive integers such as 1,2,3,...n are known as natural numbers#include <iostream>using namespace std;int main() {int num, sum;sum = 0;cout << "Enter a positive integer: ";cin >> num;for (int count = 1; count <= num; ++count) {sum += count;}cout << "Sum = " << sum << endl;return 0;}
输出
Enter a positive integer: 10Sum = 55
在上面的示例中,我们有两个变量num和sum。sum变量分配有0,num变量分配有用户提供的值。
请注意,我们使用了for循环。
for(int count = 1; count <= num; ++count)
Here,
int count = 1:初始化count变量count <= num:只要count小于或等于num,就运行循环++count:每次迭代将count变量增加 1
当count变为11时,condition为false,并且sum等于0 + 1 + 2 + ... + 10。
基于范围的for循环
在 C++ 11 中,引入了一个新的基于范围的for循环来处理诸如数组和向量之类的集合。 其语法为:
for (variable : collection) {// body of loop}
在此,对于collection中的每个值,都会执行for循环,并将该值分配给var。
示例 4:基于范围的循环
#include <iostream>using namespace std;int main() {int num_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};for (int n : num_array) {cout << n << " ";}return 0;}
输出
1 2 3 4 5 6 7 8 9 10
在上面的程序中,我们声明并初始化了一个名为num_array的int数组。 它有 10 个项目。
在这里,我们使用了基于范围的for循环来访问数组中的所有项目。
C++ 无限循环
如果for循环中的condition始终为true,则它将永远运行(直到内存已满)。 例如,
// infinite for loopfor(int i = 1; i > 0; i++) {// block of code}
在上面的程序中,condition始终为true,它将无限次运行代码。
查看以下示例以了解更多信息:
在下一个教程中,我们将学习while和do...while循环。
