第八講:條件語句與選擇語句
一、條件語句的語法規則
if (條件表達式)//條件能夠是一個表達式,多個表達式,也能夠是一個函數
{
}
else
{
}
例:class Program
{
static void Main(string[] args)
{
Console.WriteLine("請輸入姓名:");
string name = Console.ReadLine();數組
Console.WriteLine("請輸入性別:");
string sex = Console.ReadLine();ide
string nname;
if (sex == "男")
{
nname = "先生";
}
else
{
nname = "女士";
}
if (DateTime.Now.Hour >= 12)
{
Console.WriteLine("{0}{1},上午好!",name,nname);
}
else
{
Console.WriteLine("{0}{1},下午好!", name, nname);
}
}
}
二、選擇語句:出現多個條件時,能夠使用switch...case語句,但它不能應用於範圍。
語法結構:switch()
{
case 常量:
語句塊
break;
case 常量:
語句塊
break;
default:
break;
}函數
注意:全部case後面的值不能相同,每一個case語句塊後必須有一個break跳出語句,若是case後沒有語句塊能夠不用break,switch()中應該是string或值類型。
例:class Program
{
static void Main(string[] args)
{
int score=int.Parse(Console.ReadLine());
switch(score/10)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
Console.WriteLine("不及格!");
break;
case 6:
case 7:
case 8:
Console.WriteLine("良好!");
break;
case 9:
case 10:
Console.WriteLine("優秀!");
break;
default:
Console.WriteLine("成績格式不正確!");
break;
}
}
}
第九講:循環語句
一、for循環:語法格式:
for (int i = 0; i <= 10;i++)
{spa
}
例1:1到100的和
namespace Chapter9Demo1
{
class Program
{
static void Main(string[] args)
{
int sum = 0;
for (int i = 1; i <= 100;i++ )
{
sum = sum + i;
}
Console.WriteLine(sum);
Console.ReadKey();
}對象
}
}
例2:乘法口訣
namespace Chapter9Demo1
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i < 10; i++)
{
for (int j = 1; j <=i; j++)
{
Console.Write("{0}*{1}={2}"+" ",i,j,i*j);
}
Console.WriteLine();
}
Console.ReadKey();
}string
}
}
二、while循環
例:class Program
{
static void Main(string[] args)
{
int i = 0;
while(i<5)
{
Console.WriteLine(i++);
}
}
}
三、do{ }while循環
例:int i = 0;
do
{
Console.WriteLine(i++);
} while (i < 5);
四、foreach語句遍歷數組或對象集合中的每一個元素。
foreach(類型 變量 in 類型數組或類集合)
{
}
例:static void Main(string[] args)
{
int[] arrint = new int[] { 1, 2, 3, 4, 5 };
foreach(int i in arrint)
{
Console.WriteLine(i);
}
}
五、break,continue語句
break:語句用於終止最近的封閉循環,跳出全部循環。
continue:跳過本次循環,執行下次循環。
例:class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 100; i++)
{
if (i<20)
{
break;
// continue;
}
Console.WriteLine(i);
}
}it