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

Looping Techniques ใน C# (เทคนิคการวนลูป)

Loop Statement ใช้สำหรับรันคำสั่งหรือกลุ่มคำสั่งหลายครั้ง C# รองรับ Loop หลัก 3 แบบ:

ลำดับLoop Type และ คำอธิบาย
1while loop - วนรอบขณะเงื่อนไขเป็นจริง ตรวจสอบก่อนเข้าลูป
2for loop - วนรอบจำนวนครั้งที่กำหนด จัดการ Loop Variable ให้อัตโนมัติ
3do...while loop - คล้าย while แต่ตรวจสอบเงื่อนไขท้ายลูป (รันอย่างน้อย 1 รอบ)

C# ยังมี foreach สำหรับวนลูปผ่าน Collection

ตัวอย่าง foreach

using System;
using System.Collections;

class Demo
{
    static void Main()
    {
        bool[] arr = new bool[5];
        arr[0] = true;
        arr[1] = true;
        arr[2] = false;
        arr[3] = false;
        BitArray bArr = new BitArray(arr);
        foreach (bool b in bArr)
        {
            Console.WriteLine(b);
        }
        bool str = arr[1];
        Console.WriteLine("Value of 2nd element: " + str);
    }
}