ภาพรวม
คำสั่ง for loop ใน C# ใช้สำหรับ วนลูปด้วยดัชนี (Index) เหมาะสำหรับการเข้าถึง อ่าน เขียน อาร์เรย์โดยตรง ให้ของควบคุมครบครัน: เริ่มต้น, เงื่อนไข, การเพิ่ม/ลด
ตัวอย่างโปรแกรม
using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int[] n = new int[10]; // อาร์เรย์ 10 จำนวนเต็ม
int i, j;
// 1. เริ่มต้นค่า: n[i] = i + 100
for (i = 0; i < 10; i++)
n[i] = i + 100;
// 2. แสดงค่าด้วย For Loop (มี Index)
for (j = 0; j < 10; j++)
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
// 3. เข้าถึงองค์ประกอบเฉพาะตัว (Random Access)
int a = n[2]; // ดัชนี 2 = องค์ประกอบที่ 3
Console.WriteLine(a); // 102
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 102
โครงสร้าง For Loop
for (init; condition; increment)
{
// Body
}| ส่วน | คำอธิบาย | ตัวอย่าง |
|---|---|---|
| Init | รันครั้งแรก ก่อนเข้าลูป | int i = 0 |
| Condition | ตรวจสอบก่อนแต่ละรอบ | i < 10 |
| Increment | รันหลังแต่ละรอบ | i++ |
รูปแบบ For Loop ต่างๆ
1. For Loop มาตรฐาน (0 ถึง Length-1)
for (int i = 0; i < arr.Length; i++)
Console.WriteLine(arr[i]);2. For Loop ย้อนกลับ (Reverse)
for (int i = arr.Length - 1; i >= 0; i--)
Console.WriteLine(arr[i]);3. For Loop ข้ามทีละ 2 (Step)
for (int i = 0; i < arr.Length; i += 2)
Console.WriteLine(arr[i]); // Index คู่4. For Loop หลายตัวแปร
for (int i = 0, j = arr.Length - 1; i < j; i++, j--)
{
Swap(arr[i], arr[j]); // Reverse Array
}5. For Each (ไม่ใช่ For แตกต่างคนละคำสั่ง)
foreach (int val in arr)
Console.WriteLine(val); // ไม่มี Indexการเข้าถึงองค์ประกอบเฉพาะ
int thirdElement = n[2]; // ดัชนี 2 = ตัวที่ 3 (Zero-based) Console.WriteLine(thirdElement); // 102
ข้อสังเกตสำคัญ
- For Loop ให้ Control ทุกอย่าง: Index, Condition, Step
- เหมาะสำหรับ: ต้องการ Index, แก้ไขค่าใน Array, วนย้อนกลับ, Step ไม่คงที่
- Array.Bounds Checking เกิดขึ้นทุกครั้งที่เข้าถึง
arr[i](JIT อาจ Optimize ทิ้งได้ในบางกรณี) - หลีกเลี่ยง Off-by-one Error: ใช้
i < Lengthไม่ใช่i <= Length - สำหรับอ่านอย่างเดียว ไม่ต้องการ Index → ใช้
foreachอ่านง่ายกว่า