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
| คุณสมบัติ | while | do-while |
|---|---|---|
| Check Condition | ก่อนรัน (Pre-test) | หลังรัน (Post-test) |
| Minimum Iterations | 0 | 1 |
| ใช้เมื่อ | อาจไม่ต้องรันเลย | ต้องรันอย่างน้อย 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