📅  最后修改于: 2023-12-03 15:29:43.694000             🧑  作者: Mango
在C语言中,控制结构是控制程序流程的重要方式。下面介绍一些常见的控制结构。
if-else语句用于根据条件执行不同的代码块。下面是if-else语句的语法:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
例子:
int num = 10;
if(num > 5) {
printf("Number is greater than 5.\n");
} else {
printf("Number is not greater than 5.\n");
}
switch语句用于根据不同的情况执行不同的代码块。下面是switch语句的语法:
switch (expression) {
case constant1:
// code to be executed if expression is equal to constant1
break;
case constant2:
// code to be executed if expression is equal to constant2
break;
...
default:
// code to be executed if all cases are not matches
}
例子:
int day = 3;
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
default:
printf("Invalid day");
}
for循环用于重复执行某一段代码。下面是for循环的语法:
for (initialization; condition; increment) {
// code to be executed
}
例子:
for(int i = 1; i <= 5; i++) {
printf("%d ", i);
}
while循环用于根据某个条件重复执行某一段代码。下面是while循环的语法:
while (condition) {
// code to be executed
}
例子:
int i = 1;
while(i <= 5) {
printf("%d ", i);
i++;
}
do-while循环用于至少执行一次某一段代码,然后根据某个条件重复执行。下面是do-while循环的语法:
do {
// code to be executed
} while (condition);
例子:
int i = 1;
do {
printf("%d ", i);
i++;
} while(i <= 5);
这些控制结构可以帮助程序员更好地控制程序流程,实现复杂的功能逻辑。