ในการวนลูปผ่านอาร์เรย์ใน C# ใช้ลูปได้ทุกแบบ while, do-while, for, foreach ซึ่งมีค่าเริ่มต้นและสิ้นสุดสำหรับตรวจสอบค่าผ่านการวนซ้ำ
ตัวอย่าง for loop
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]; - Initialize ด้วย for loop:
n[i] = i + 10;(i เพิ่มจาก 0 ถึง 9) - วนลูปแสดงผล:
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
ผลลัพธ์
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