判断和循环语句
目录:
- 判断语句及其分析
- 循环语句及其分析
- 注意事项
一.判断语句
- if
(1)布尔表达式加多个语句组成
(2)
int a = 9 ;
if (a < 15)
{
Console. WriteLine(“a小于15”);
}`
- if…else
(1)布尔表达式判断真假执行语句
if(//判断语句)
{执行语句
}
else
{执行语句
}
- switch
(1)可以拥有任意数量的case
(2)当被测试的变量等于 case 中的常量时,case 后跟的语句将被执行,直到遇到 break 语句为止。
(3)当遇到 break 语句时,switch 终止,控制流将跳转到 switch 语句后的下一行。
switch(expression){
case constant-expression :
statement(s);
break;
case constant-expression :
statement(s);
break;
/* 您可以有任意数量的 case 语句 */
default : /* 可选的 */
statement(s);
break;
}
- 嵌套
(1)在if或if… else嵌套另一个if或if…else
(2)在switch 中嵌套另一个switch
二.循环语句
- while循环
(1)重复语句和语句组,执行循环主体之前的测试,结果为真时继续循环
while(condition)
{
statement(s);
}
- for/foreach循环
(1)多次执行一个语句序列,简化管理循环变量的代码
for(init; condition; increment)
{
statement(s);
}
(2)init只会执行一次,可声明并初始化任何循环控制变量
(3)condition会判断,为真则循环,为假则控制流跳转到for循环吓一条语句
(4)increment语句,允许更新循环控制变量,可留空,要在条件后加一个分号
- do…while循环
do
{
statement(s);
}while( condition );
(1)在循环结尾测试条件有所不同
(2)statement会被不止执行一次
(3)当条件为真时,循环语句会不断执行
- 嵌套
(1)for/while/do…while中嵌套一个相应语句
for/while/do...while ( init; condition; increment )
{
for/while/do...while ( init; condition; increment )
{
statement(s);
}
statement(s);
}
注意事项:for循环可以嵌套一个while