如何迴圈處理一個 C# 陣列?


為了迴圈處理 C# 中的陣列,請使用任何一個迴圈。這些迴圈具有設定的起始和結束值,允許你在迭代中設定或檢查值。

C# 具有 while、do…while、for 和 foreach 迴圈來迴圈處理陣列。

讓我們在 C# 中看一個 for 迴圈的例子 −

示例

 即時演示

using System;

namespace ArrayApplication {
   class MyArray {
      static void Main(string[] args) {
         int [] n = new int[10];
         int i,j;

         for ( i = 0; i < 10; i++ ) {
            n[ i ] = i + 10;
         }

         for (j = 0; j < 10; j++ ) {
            Console.WriteLine("Element[{0}] = {1}", j, n[j]);
         }
         Console.ReadKey();
      }
   }
}

現在讓我們看看上面如何迴圈處理陣列的。

10 個整數的陣列 −

int [] n = new int[10];

現在,初始化上面宣告的陣列的元素 −

for ( i = 0; i < 10; i++ ) {
   n[ i ] = i + 10;
}

以上的迴圈從 i=0 到 i = 10 進行迭代,在每次迭代之後 i 的值遞增 −

i++;

在每次從 i = 10 的迭代中,該值被新增到陣列中,起始元素為 10 −

n[ i ] = i + 10;

輸出

Element[0] = 10
Element[1] = 11
Element[2] = 12
Element[3] = 13
Element[4] = 14
Element[5] = 15
Element[6] = 16
Element[7] = 17
Element[8] = 18
Element[9] = 19

更新日期:20-6 月-2020 年

5000+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲取認證

開始
廣告