📜  C |回路和控制结构|问题16(1)

📅  最后修改于: 2023-12-03 15:29:43.616000             🧑  作者: Mango

C语言中的回路和控制结构

C语言中有很多回路和控制结构可以让程序员灵活地控制代码的执行。

if语句

if语句可以根据判断条件选择性地执行一段代码块:

if (condition) {
    // code to be executed if condition is true
}

例如:

int x = 10;
if (x > 5) {
    printf("x is greater than 5\n");
}

输出:

x is greater than 5
if...else语句

if...else语句可以根据判断条件分别执行两段代码块:

if (condition) {
    // code to be executed if condition is true
} else {
    // code to be executed if condition is false
}

例如:

int x = 10;
if (x > 5) {
    printf("x is greater than 5\n");
} else {
    printf("x is less than or equal to 5\n");
}

输出:

x is greater than 5
switch语句

switch语句可以根据表达式的值匹配执行不同的代码块:

switch (expression) {
case value1:
    // code to be executed if expression matches value1
    break;
case value2:
    // code to be executed if expression matches value2
    break;
...
default:
    // code to be executed if expression doesn't match any of the values
    break;
}

例如:

int day = 5;
switch (day) {
case 1:
    printf("Monday\n");
    break;
case 2:
    printf("Tuesday\n");
    break;
case 3:
    printf("Wednesday\n");
    break;
case 4:
    printf("Thursday\n");
    break;
case 5:
    printf("Friday\n");
    break;
case 6:
    printf("Saturday\n");
    break;
case 7:
    printf("Sunday\n");
    break;
default:
    printf("Invalid day\n");
    break;
}

输出:

Friday
while循环

while循环可以重复执行一段代码块,直到条件不再满足为止:

while (condition) {
    // code to be executed repeatedly while condition is true
}

例如:

int i = 0;
while (i < 5) {
    printf("%d ", i);
    i++;
}

输出:

0 1 2 3 4
do...while循环

do...while循环与while循环类似,但是它会先执行一次代码块,再判断条件:

do {
    // code to be executed repeatedly at least once
} while (condition);

例如:

int i = 0;
do {
    printf("%d ", i);
    i++;
} while (i < 5);

输出:

0 1 2 3 4
for循环

for循环可以重复执行一段代码块,可以自定义循环变量的初始值、条件和增量:

for (initialize; condition; increment) {
    // code to be executed repeatedly while condition is true
}

例如:

for (int i = 0; i < 5; i++) {
    printf("%d ", i);
}

输出:

0 1 2 3 4
break语句

break语句可以让程序跳出当前循环或switch语句:

while (condition) {
    // code to be executed repeatedly while condition is true
    if (some_condition) {
        break; // breaks out of the loop
    }
}
switch (expression) {
case value1:
    // code to be executed if expression matches value1
    break;
case value2:
    // code to be executed if expression matches value2
    break;
...
default:
    break; // breaks out of the switch statement
}
continue语句

continue语句可以让程序跳过当前循环中的某个迭代:

while (condition) {
    // code to be executed repeatedly while condition is true
    if (some_condition) {
        continue; // skips the rest of the current iteration
    }
}
for (int i = 0; i < 5; i++) {
    if (i == 2) {
        continue; // skips the third iteration
    }
    printf("%d ", i);
}

输出:

0 1 3 4

以上是C语言中的回路和控制结构的简单介绍。熟练掌握这些结构可以让程序员更好地控制代码的执行,提高代码的效率。