if语句
if语句实现按条件执行,if语句语法如下所示:
1 if <test> 2 { 3 <code executed if <test> is true>; 4 }
- TestExpr必须计算成bool型值。
- 如果TestExpr求值为true,Statement被执行。
- 如果TestExpr求值为false,Statement被跳过。
1 if <test> 2 { 3 <code executed if <test> is true>; 4 } 5 else 6 { 7 <code executed if <test> is false>; 8 }
switch语句
switch语句非常类似于if语句,因为它也是根据测试的值来有条件地执行代码。但是,switch语句可以一次将测试变量与多个值进行比较,而不是仅测试一个条件。
switch语句的基本结构如下:
1 switch (<testVar>) 2 { 3 case <comparisonVal1>: 4 <code to execute if <testVar> == <comparisonVal1>> 5 break; 6 case<comparisonVal2>: 7 <code to execute if <testVar> ==<comparisonVal2>> 8 break; 9 ... 10 case<comparisonValN>: 11 <code to execute if <testVar>==<comparisonValN>> 12 break; 13 default: 14 <code to execute if <testVar>!=comparisonVals> 15 break; 16 }
<testVar>中的值与每个<comparisonValX>值(在case语句中指定)进行比较,如果有一个匹配,就执行为该匹配提供的语句。如果没有匹配,就执行default语句中的代码。执行完每个部分中的代码后,还需有另一个语句break。在执行完一个case块后,再执行第二个case语句是非法的。
do循环
do循环的机构如下:
1 do 2 { 3 <code to be loped> 4 }while (<Test>);
例如:使用该结构可以把1~10的数字输出到一列上:
1 int i = 1; 2 do 3 { 4 Console.WriteLine("{0}", i++) 5 } 6 while (i <= 10);
while循环
while循环非常类似于do循环,但有一个明显的区别:while循环中布尔测试实在循环开始时进行,而不是在最后。
while循环的机构如下:
1 whle (<test>) 2 do 3 { 4 <code to be loped> 5 }
使用while循环修改do循环示例:
1 int i = 1; 2 while (i <= 10) 3 { 4 Console.WriteLine("{0}", i++); 5 }
for循环
要定义for循环,需要以下信息:
- 初始化计数器变量的一个起始值;
- 继续循环的条件,它应设计到计数器变量;
- 在每次循环的最后,对计数器变量执行一个操作
for循环的机构如下:
1 for (<initialization>; <condition>; <operation>) 2 { 3 <code to loop> 4 }
使用for循环修改上面的示例:
1 int i; 2 for (i = 1; i <= 10; i++) 3 { 4 Console.WriteLine("{0}", i); 5 }
循环的中断
- break——立即终止循环。
- continue——立即终止当前的循环(继续执行下一次循环)。
- goto——可以跳出循环,到已标记好的位置上(如果希望代码易于阅读和理解,最好不要使用该命令)。
- return——跳出循环及其包含的函数。