
循环是编程中必不可少的工具,它允许我们重复执行一段代码。它们可以执行各种任务,从简单的计算到复杂的数据处理。
在 c 编程中,我们有三种主要的循环类型:for、while 和 do-while。让我们通过示例来探讨它们。
当我们确切知道要重复一段代码多少次时,for 循环是默认选择。这就像为我们的代码设置一个计时器来运行特定次数。
// syntax
for (initialization; condition; increment/decrement) {
// code to be executed in each iteration
}
// example
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
printf("\n"); // output: 1 2 3 4 5
return 0;
}
在此示例中,for 循环打印从 1 到 5 的数字。初始化 ( int i = 1; ) 设置计数器变量 i 的起始值。条件 ( i <= 5; ) 指定只要 i 小于或等于 5 就应继续循环。每次迭代后,增量 ( i++ ) 将 i 的值增加 1。
while循环就像一个条件循环。只要条件保持为真,它就会不断旋转(执行代码块)。
// syntax
while (condition) {
// code to be executed repeatedly
}
// example
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
printf("\n"); // output: 1 2 3 4 5
return 0;
}
这个 while 循环实现与上面的 for 循环相同的结果。它打印从 1 到 5 的数字,但计数器变量 i 在循环结构之外初始化并递增。
do-while 循环坚持至少执行代码块一次,即使条件最初为 false。
// syntax
do {
// Code to be executed repeatedly
} while (condition);
// example
#include <stdio.h>
int main() {
int i = 6; // Notice i is initialized to 6
do {
printf("%d ", i);
i++;
} while (i <= 5);
printf("\n"); // Output: 6
return 0;
}
即使条件 i <= 5 从一开始就是 false,do-while 循环仍然执行代码块一次,打印 i 的值 (即 6).
循环的用途非常广泛,并且在编程中具有广泛的应用:
最后,由于循环是编程的基础,因此在 c 语言中理解循环将为您学习其他语言(如 python、javascript 和 java)做好准备。
以上就是C 中的循环:带有示例的简单指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号