1.switch结构:
#include <stdio.h>
main(){
switch(表达式){
case 常量表达式1:
语句1 break ;//break表示停止,即跳出循环,之后细🔒
case 常量表达式2:
语句2 break;
case 常量表达式3:
语句3 break;
default:
语句n+1;
}
}
ps:与 if 语句的不同:if 语句中若判断为真则只执行这个判断后的语句,执行完就跳出 if 语句,不会执行其他 if 语句;而 switch 语句不会在执行判断为真后的语句之后跳出循环,而是继续执行后面所有 case 语句。在每一 case 语句之后增加 break 语句,使每一次执行之后均可跳出 switch 语句,从而避免输出不应有的结果。
2.while循环:
a.while(表达式){
语句
}
b.do{
语句
}while(表达式)
ps:while语句是先判断条件再执行语句,do...while语句是先执行语句再判断条件。
#include <stdio.h>
main(){
int a;
a=1;
while(a<=5){
a++;
}
printf("%d",a);
}
#include <stdio.h>
main(){
int a;
a=1;
do{
a++;
}while(a<=5)
printf("%d",a);
}
3.for循环:
for(表达式1;表达式2;表达式3){
语句;
}
运行过程:(1):先执行表达式1
(2):再执行表达式2,如果它的值为真,则执行循环体即语句,否则结束循环
(3):执行完循环体后再执行表达式3
(4):重复执行步骤(2),(3)直到表达式2的值为假
#include <stdio.h>
main(){
int a;
for(a=0;a<=5;a++){
printf("%d\n",a);
}
}
本文介绍了C语言中的switch结构,强调了它与if语句的区别,以及while、do...while和for循环的执行逻辑。通过实例展示了如何使用这些控制结构来控制程序流程。
10万+

被折叠的 条评论
为什么被折叠?



