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

การใช้ Do-While Loop ใน C#

do-while Loop ตรวจสอบเงื่อนไข **หลัง** รัน Body เสร็จแล้ว **รันอย่างน้อย 1 ครั้งเสมอ**

Syntax

do
{
    // Statements
} while (condition); // ต้องมี Semicolon

โค้ดตัวอย่าง

using System;

namespace Loops
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 50;
            
            // รันก่อน เช็คทีหลัง
            do
            {
                Console.WriteLine("Value of a: {0}", a);
                a = a + 1;
            } while (a < 20); // False ทันที แต่รัน 1 รอบแล้ว
            
            Console.ReadLine();
        }
    }
}

ผลลัพธ์

Value of a: 50

While vs Do-While

คุณสมบัติwhiledo-while
Check Conditionก่อนรัน (Pre-test)หลังรัน (Post-test)
Minimum Iterations01
ใช้เมื่ออาจไม่ต้องรันเลยต้องรันอย่างน้อย 1 รอบ

ตัวอย่างใช้งานจริง: Menu System

string input;
do
{
    Console.WriteLine("1. Add");
    Console.WriteLine("2. Delete");
    Console.WriteLine("3. Exit");
    Console.Write("Choose: ");
    input = Console.ReadLine();
    
    switch (input)
    {
        case "1": Console.WriteLine("Adding..."); break;
        case "2": Console.WriteLine("Deleting..."); break;
    }
} while (input != "3");

Best Practice

  • ใช้ while เป็นหลัก (อ่านง่ายกว่า)
  • ใช้ do-while เฉพาะเมื่อ Logic ต้องการรันก่อนเช็ค (Menu, Input Validation, Retry Logic)
  • ระวัง Infinite Loop - ต้องมีการเปลี่ยน Condition ภายใน Loop