Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีวนลูปอาร์เรย์จำนวนเต็มขนาดไม่ทราบล่วงหน้าใน C#

สร้างอาร์เรย์โดยไม่กำหนดขนาด:

int[] arr = new int[] { 5, 7, 2, 4, 1 };

ใช้ Length และลูป for:

for (int i = 0; i < arr.Length; i++) {
    Console.WriteLine(arr[i]);
}

ตัวอย่าง

using System;
public class Program {
    public static void Main() {
        int[] arr = new int[] { 5, 7, 2, 4, 1 };
        Console.WriteLine("Length:" + arr.Length);
        for (int i = 0; i < arr.Length; i++) {
            Console.WriteLine(arr[i]);
        }
    }
}

ผลลัพธ์

Length:5
5
7
2
4
1