for循环中使用case
时间: 2024-04-24 11:23:31 浏览: 9
在C语言中,我们通常使用`switch`语句来实现多个条件的选择。`switch`语句可以与`for`循环结合使用,以在每次循环迭代中根据不同的条件执行不同的代码块。
这是一个使用`switch`语句和`for`循环的示例:
```c
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 5; i++) {
switch (i) {
case 1:
printf("i is 1\n");
break;
case 2:
printf("i is 2\n");
break;
case 3:
printf("i is 3\n");
break;
default:
printf("i is not 1, 2, or 3\n");
break;
}
}
return 0;
}
```
在上面的示例中,`for`循环从1到5进行迭代,而在每次迭代中,`switch`语句根据`i`的值执行相应的代码块。如果`i`的值为1,将打印"i is 1";如果`i`的值为2,将打印"i is 2";如果`i`的值为3,将打印"i is 3";如果`i`的值不是1、2或3,将打印"i is not 1, 2, or 3"。