一,C语言分支语句
在编程中,分支语句用于根据某些条件执行特定的代码块。C语言提供了两种主要的分支语句:if
和 switch
。
1,if语句
if
语句用于根据某个条件执行代码块。它的基本语法如下:
if (condition) {
// 代码块
}
如果 condition
为真(非零),则执行 if
语句后的代码块。否则,跳过 if
语句后的代码块。
例如:
int x = 5;
if (x > 3) {
printf("x is greater than 3");
}
在这个例子中,x > 3
为真,因此会打印出 "x is greater than 3"。
2,if...else语句
if...else
语句用于在条件为假时执行备选代码块。它的基本语法如下:
if (condition) {
// 代码块1
} else {
// 代码块2
}
如果 condition
为真,则执行代码块1;否则执行代码块2。
例如:
int x = 5;
if (x > 10) {
printf("x is greater than 10");
} else {
printf("x is less than or equal to 10");
}
在这个例子中,x > 10
为假,因此会打印出 "x is less than or equal to 10"。
3,switch语句
switch
语句用于根据表达式的值执行不同的代码块。它的基本语法如下:
switch (expression) {
case constant1:
// 代码块1
break;
case constant2:
// 代码块2
break;
...
default:
// 默认代码块
}
表达式会被求值,并与每个 case
中的常量进行比较。如果找到匹配的 case
,则执行相应的代码块,然后跳出 switch
语句。如果没有找到匹配的 case
,则执行 default
代码块(可选)。如果没有 default
代码块,则跳出 switch
语句。每个 case
后通常都有一个 break
语句,用于防止执行下一个 case
的代码块。
例如:
int day = 2;
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
default:
printf("Another day");
}
在这个例子中,day
的值为2,因此会打印出 "Tuesday"。
二,C语言循环语句
循环语句用于重复执行一段代码,直到满足某个条件。C语言提供了三种主要的循环语句:for
、while
和 do...while
。
1,for循环语句
for
循环语句通常用于已知循环次数的情况。它的基本语法如下:
for (initialization; condition; increment/decrement) {// code block}
在循环开始前,先执行 initialization 表达式。然后检查 condition 是否为真。如果为真,则执行 code block,然后执行 increment/decrement 表达式。这个过程会一直重复,直到 condition 为假。例如:
for (int i = 0; i < 5; i++)
{
printf("%d ", i);
}
这个例子会打印出 "0 1 2 3 4 "。
2.while循环语句
while
循环语句通常用于未知循环次数的情况。它的基本语法如下:
while (condition) {// code block}
只要 condition 为真,就执行 code block。例如:
int i = 0;while (i < 5)
{
printf("%d ", i); i++;
}
这个例子会打印出 "0 1 2 3 4 "。
3,do...while循环语句
循环语句do...while
与 while
很相似,但是它会先执行一次 code block,然后再检查 condition。如果 condition 为真,则继续循环。它的基本语法如下:
do
{
// code block
} while (condition);
例如:
int i = 0;
do
{
printf("%d ", i);
i++;
} while (i < 5);
这个例子会打印出“0 1 2 3 4”。