Loop.txt ---------- 20190425 do, while, for, foreach, break, continue 統一參考 loop.txt 為準. ---------- Do-While public class TestDoWhile { public static void Main () { int x = 0; do { Console.WriteLine(x); x++; } while (x < 5); } } /* Output: 0 1 2 3 4 */ ---------- for class ForLoopTest { static void Main() { for (int i = 1; i <= 5; i++) { Console.WriteLine(i); } } } /* Output: 1 2 3 4 5 */ ---------- ForEach class ForEachTest { static void Main(string[] args) { int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 }; foreach (int element in fibarray) { System.Console.WriteLine(element); } System.Console.WriteLine(); // Compare the previous loop to a similar for loop. for (int i = 0; i < fibarray.Length; i++) { System.Console.WriteLine(fibarray[i]); } System.Console.WriteLine(); // You can maintain a count of the elements in the collection. int count = 0; foreach (int element in fibarray) { count += 1; System.Console.WriteLine("Element #{0}: {1}", count, element); } System.Console.WriteLine("Number of elements in the array: {0}", count); } // Output: // 0 // 1 // 1 // 2 // 3 // 5 // 8 // 13 // 0 // 1 // 1 // 2 // 3 // 5 // 8 // 13 // Element #1: 0 // Element #2: 1 // Element #3: 1 // Element #4: 2 // Element #5: 3 // Element #6: 5 // Element #7: 8 // Element #8: 13 // Number of elements in the array: 8 } ---------- while class WhileTest { static void Main() { int n = 1; while (n < 6) { Console.WriteLine("Current value of n is {0}", n); n++; } } } /* Output: Current value of n is 1 Current value of n is 2 Current value of n is 3 Current value of n is 4 Current value of n is 5 */