2.1 if语句
if(condition)
statements
else
statementes
也可以单独使用if语句,也可以合并else if语句。


1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace if语句 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 Console.WriteLine("Begin the test of if:"); 13 string input = Console.ReadLine(); 14 if (input =="") 15 { 16 Console.WriteLine("Nothing have been typed!"); 17 } 18 else if (input.Length < 2) 19 { 20 21 Console.WriteLine("less than 2!"); 22 23 24 25 } 26 27 else if (input.Length > 10) 28 { 29 30 Console.WriteLine("more than 10!"); 31 } 32 else 33 Console.WriteLine("the input is:" + input); 34 } 35 } 36 }
2.2 switch语句
switch(integA)
{
case 1:
break;
case 2:
break;
default:
}
其中,case中得值必须是常量表达式,来与integA对比,如果相同,则执行此case后面的语句,遇到break语句停止,并跳出循环,除非使用goto语句指定要跳到位置。如果case后面没有执行语句,则会自动跳到下一个case语句,如果所有的条件都不满足,那么执行default后面的语句!


1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace switch语句 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 Console.WriteLine("请输入一个国家或者地区的名字"); 13 string input=Console.ReadLine(); 14 switch(input) 15 { 16 case "美国": 17 Console.WriteLine("你是一个美国鬼子!"); 18 break; 19 case "英国": 20 Console.WriteLine("你是一个英国鬼子!"); 21 break; 22 case "中国": 23 case "台湾": 24 Console.WriteLine("你是一个中国人!"); 25 break; 26 default: 27 Console.WriteLine("你是外星人吗?"); 28 break; 29 30 31 32 33 34 35 36 37 38 } 39 } 40 } 41 }
2.3 for循环
for(initializer;condition;iterator)
statements
其中,initializer是指在第一次循环前要执行的表达式,一般用来初始化一个局部变量;condition是每次执行新的循环之前需要检测的表达式,只有等于true时才能执行下一次迭代;最后的iterator是每次迭代完要计算的表达式,通常是递增或者递减的表达式。
比如下面这段代码:


1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace for循环 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 for (int i = 0; i < 100;i+=10 ) 13 { 14 15 for (int j = i; j < i + 10 ;j++ ) 16 { 17 if(j<10) 18 Console.Write(" "+j); 19 else 20 Console.Write(" " + j); 21 22 } 23 Console.WriteLine(); 24 25 } 26 } 27 } 28 }
2.4 while语句
while(condition)
statements;
以及do`````````while语句
do
{
statement
}
while(conditions)
2.5 其他
foreach循环:主要用于数组中得遍历:
foreach(int temp in arryOfInts)
{
console.writeline(temp);
}
goto语句:可以直接跳到程序中得指定的标签,这个语句不是很常用,它不能跳到像for循环的代码中去,也不能跳出类,更不能推出try catch后面的finally块。
break语句:可以退出for、foreach、while、等循环。
continue语句:只能退出break语句中得迭代,进入下一次迭代,但是不会直接退出循环。
return语句:用于退出类得方法,后面需要接上返回类型。