todo
為什麼要使用電腦? 就是要用電腦重複幫我們作相同的工作. 所以迴圈是整個程式的靈魂
基本語法
for
for (初始值;條件式;增值)
計算1+2+..100
無初始值,需置於迴圈外
條件式可於迴圈內,用於複雜判斷式
增值 i++ , ++i, i–, –i 之差異
巢狀迴圈
for (int i=1;i<=5;i++){ for (int j=1;j<=i;j++){ Console.Write(“ {0}”,j); } Console.WriteLine(); }
while
while (判斷式){
}
判斷式有可能永遠為true, 會變成無窮迴圈,需有break退出
do…while
do{
}while(判斷式); <==需有 “;”
先作一次迴圈再判斷
break
用於for, while, switch, do
continue
continue會忽略下面的指令,直接回到迴圈第一行
直向列印
1 2 3 4 5 6 7 8 9 10 代碼 namespace ConsoleApp1 { class Program { static void Main(string[] args) { for (int i = 1; i <= 10; i++) { Console.WriteLine(i); } } } }
橫向列印
1 2 3 4 5 6 7 8 9 10 代碼 namespace ConsoleApp1 { class Program { static void Main(string[] args) { for (int i = 1; i <= 10; i++) { Console.Write("{0} ", i); } Console.WriteLine(); } } }
九九乘法表
static void Main(string[] args) { for (int i = 1; i <= 9; i++) { for (int j=1; j <= 9; j++) { Console.Write("{0, 2:d} ", i * j); } Console.WriteLine(); } } 結果 : 1 2 3 4 5 6 7 8 9 2 4 6 8 10 12 14 16 18 3 6 9 12 15 18 21 24 27 4 8 12 16 20 24 28 32 36 5 10 15 20 25 30 35 40 45 6 12 18 24 30 36 42 48 54 7 14 21 28 35 42 49 56 63 8 16 24 32 40 48 56 64 72 9 18 27 36 45 54 63 72 81
左三角
* * * * * * * * * * * * * * * 代碼 namespace ConsoleApp1 { class Program { static void Main(string[] args) { for (int i = 1; i <= 5; i++) { for (int j = 1; j <=i; j++) { Console.Write("* "); } Console.WriteLine(); } } } }
倒三角
* * * * * * * * * * * * * * * 代碼 namespace ConsoleApp1 { class Program { static void Main(string[] args) { for (int i = 1; i <= 5; i++) { for (int j = 5; j >=i; j--) { Console.Write("* "); } Console.WriteLine(); } } } }
右三角
* * * * * * * * * * * * * * * 代碼 namespace ConsoleApp1 { class Program { static void Main(string[] args) { for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 5-i; j++) { Console.Write(" "); } for (int j = 1; j <=i; j++) { Console.Write("* "); } Console.WriteLine(); } } } }
偶數
< < < < < > > > > > < < < < < > > > > > < < < < < 代碼 namespace ConsoleApp1 { class Program { static void Main(string[] args) { for (int i = 1; i <= 5; i++) { for (int j = 1; j <=5; j++) { if(i%2==0)Console.Write("> "); else Console.Write("< "); } Console.WriteLine(); } } } }
三條件相間
A A A A A B B B B B C C C C C A A A A A B B B B B 代碼 namespace ConsoleApp1 { class Program { static void Main(string[] args) { for (int i = 1; i <= 5; i++) { for (int j = 1; j <=5; j++) { if(i%3==1)Console.Write("A "); else if (i%3==2) Console.Write("B "); else Console.Write("C "); } Console.WriteLine(); } } } }