第五课:循环结构
循环结构用于重复执行某些操作,直到满足特定的退出条件。常见的循环结构包括 for 循环、while 循环 和 do-while 循环。
for 循环
for 循环通常用于已知次数的重复操作。
语法:
c
for (initialization; condition; update) {
// 循环体
}
说明:
- initialization:初始化变量。
- condition:循环的执行条件(布尔表达式)。
- update:每次循环结束后执行的操作(通常是变量更新)。
示例代码:
打印 1 到 10:
c
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
printf("%d ", i);
}
printf("\n");
return 0;
}
while 循环
while 循环适用于在条件为真时反复执行代码块。
语法:
c
while (condition) {
// 循环体
}
示例代码:
打印 1 到 10:
c
#include <stdio.h>
int main() {
int i = 1;
while (i <= 10) {
printf("%d ", i);
i++;
}
printf("\n");
return 0;
}
do-while 循环
do-while 循环先执行一次代码块,再检查条件是否为真。
语法
c
do {
// 循环体
} while (condition);
示例代码:
输入密码,直到输入正确为止:
c
#include <stdio.h>
int main() {
int password;
do {
printf("Enter password: ");
scanf("%d", &password);
} while (password != 1234);
printf("Access granted!\n");
return 0;
}
循环的控制语句
break
- 用于立即退出循环。
示例代码:找到第一个能被7整除的数。
c
#include <stdio.h>
int main() {
for (int i = 1; i <= 100; i++) {
if (i % 7 == 0) {
printf("First number divisible by 7: %d\n", i);
break;
}
}
return 0;
}
continue
- 用于跳过当前循环的剩余部分,直接进入下一次循环。
示例代码:跳过打印偶数。
c
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // 跳过偶数
}
printf("%d ", i);
}
printf("\n");
return 0;
}
无限循环
- 当循环条件总是为真时,会导致无限循环。
示例代码
c
#include <stdio.h>
int main() {
int i = 1;
while (1) { // 条件始终为真
printf("%d ", i++);
if (i > 10) {
break; // 防止程序卡死
}
}
printf("\n");
return 0;
}
综合练习
编写一个猜数字游戏:程序生成 1 到 100 的随机数,用户需要猜这个数,程序提示“高了”或“低了”,直到猜对为止。
代码
c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand((unsigned)time(NULL));
int target = rand() % 100 + 1; // 随机数
int guess;
printf("Guess the number (1-100):\n");
while (1) {
scanf("%d", &guess);
if (guess > target) {
printf("Too high. Try again.\n");
} else if (guess < target) {
printf("Too low. Try again.\n");
} else {
printf("Correct! The number was %d.\n", target);
break;
}
}
return 0;
}