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


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

序號迴圈型別和說明
1while 迴圈
只要給定的條件為真,它就會重複執行語句或一組語句。它在執行迴圈體之前測試條件。
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

更新日期: 20-6-2020

105 次瀏覽

開啟你的職業生涯

完成課程,獲得認證

入門
廣告
© . All rights reserved.