
1. while loop พื้นฐาน
while (เงื่อนไข) {
// คำสั่งที่จะทำซ้ำ
}
ตัวอย่าง:
int i = 0;
while (i < 5) {
cout << i << " ";
i++;
}
// ผลลัพธ์: 0 1 2 3 4
2. do-while loop
do {
// คำสั่งที่จะทำซ้ำ
} while (เงื่อนไข);
ตัวอย่าง:
int i = 0;
do {
cout << i << " ";
i++;
} while (i < 5);
// ผลลัพธ์: 0 1 2 3 4
3. while loop กับการอ่านข้อมูล
string input;
while (cin >> input) {
cout << "คุณป้อน: " << input << endl;
if (input == "exit") break;
}
4. while loop ไม่มีที่สิ้นสุด (Infinite loop)
while (true) {
// คำสั่งที่จะทำซ้ำไปเรื่อยๆ
// ต้องมีเงื่อนไขการหยุด (break) ภายในลูป
}
5. while loop กับ multiple conditions
int x = 0, y = 10;
while (x < 5 && y > 0) {
cout << x << ":" << y << " ";
x++;
y--;
}
// ผลลัพธ์: 0:10 1:9 2:8 3:7 4:6
6. while loop กับ flag variable
bool keepRunning = true;
while (keepRunning) {
// ทำงานบางอย่าง
// ...
if (someCondition) {
keepRunning = false; // หยุด loop เมื่อเงื่อนไขเป็นจริง
}
}
7. Nested while loops
int i = 0;
while (i < 3) {
int j = 0;
while (j < 3) {
cout << "(" << i << "," << j << ") ";
j++;
}
cout << endl;
i++;
}
// ผลลัพธ์:
// (0,0) (0,1) (0,2)
// (1,0) (1,1) (1,2)
// (2,0) (2,1) (2,2)
หมายเหตุ:
- while loop ตรวจสอบเงื่อนไขก่อนทำงานในลูป
- do-while loop ทำงานในลูปอย่างน้อยหนึ่งครั้งก่อนตรวจสอบเงื่อนไข
- สามารถใช้
break
เพื่อออกจาก loop ก่อนครบรอบ - สามารถใช้
continue
เพื่อข้ามการทำงานในรอบปัจจุบันและไปยังรอบถัดไป - ระวังการใช้ while loop แบบไม่มีที่สิ้นสุด (infinite loop) โดยไม่ตั้งใจ
- ควรมีการเปลี่ยนแปลงค่าที่ใช้ในเงื่อนไขภายใน loop body เพื่อป้องกัน infinite loop