C# 中支援哪些型別的迴圈?


迴圈語句允許我們多次執行語句或一組語句。C# 中支援以下迴圈 −

序號迴圈型別和說明
1while 迴圈
在給定條件為 true 時重複一條語句或一組語句。它在執行迴圈體之前測試條件。
2for 迴圈
多次執行一系列語句並縮寫管理迴圈變數的程式碼。
3do...while 迴圈
類似於 while 語句,但它在迴圈體末尾測試條件

藉助 C#,還可以使用 foreach 迴圈,如下所示 −

示例

 活動演示

using System;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         int [] n = new int[10]; /* n is an array of 10 integers */

         /* initialize elements of array n */
         for ( int i = 0; i < 10; i++ ) {
            n[i] = i + 100;
         }

         /* output each array element's value */
         foreach (int j in n ) {
            int i = j-100;
            Console.WriteLine("Element[{0}] = {1}", i, j);
         }
         Console.ReadKey();
      }
   }
}

輸出

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

更新日期: 2020 年 6 月 20 日

105 次瀏覽

啟動你的 職業

完成課程獲得認證

開始學習
廣告
© . All rights reserved.