在C语言中,分支语句主要由if、else if和else关键字构成。这些语句允许我们根据特定条件执行不同的代码块。
if语句:它用来测试一个条件,如果条件为真,则执行紧随其后的代码块。例如:
if (condition) {
// code to be executed if condition is true
}
else if语句:它用来在if语句的条件为假时测试另一个条件。例如:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition1 is false and condition2 is true
}
else语句:当所有前面的条件都为假时,执行此处的代码块。例如:
if (condition1) {
// code to be executed if condition1 is true
} else {
// code to be executed if condition1 is false
}
循环语句:
循环语句允许我们重复执行一段代码,直到满足某个条件为止。C语言提供了几种类型的循环语句,包括for、while和do while循环。
for循环:它允许你定义一个计数器变量,并在循环体中指定计数器的起始值、条件和增量。例如:
for (int i = 0; i < 10; i++) {
// code to be executed 10 times, with i incrementing from 0 to 9
}
while循环:它根据一个条件来决定是否执行循环体。如果条件为真,循环体会一直执行,直到条件变为假。例如
while (condition) {
// code to be executed repeatedly until condition becomes false
}
do while循环:与while循环类似,但循环体会先执行一次,然后再检查条件。如果条件为真,循环体会继续执行,直到条件变为假。例如:
do {
// code to be executed repeatedly until condition becomes false
} while (condition);