ลูป (Loops) ในการเขียนโปรแกรมใช้สำหรับรันบล็อกโค้ดซ้ำหลายครั้ง ที่นี่เราจะเปรียบเทียบสองประเภทของลูป: For Loop และ While Loop
For Loop
For Loop เป็นลูปควบคุมการทำซ้ำที่รันบล็อกโค้ดจำนวนครั้งที่กำหนดไว้ล่วงหน้า
Syntax
for (initialization; condition; update) {
// code to be repeated
}
While Loop
While Loop เป็นลูปควบคุมเงื่อนไขเข้าลูป (entry-controlled) ที่รันคำสั่งซ้ำจนกว่าเงื่อนไขจะเป็นเท็จ
Syntax
while (condition) {
// code to be repeated
}
ความแตกต่างหลักระหว่าง For และ While
- For Loop: ควบคุมด้วยตัวนับ (iteration-controlled) เหมาะเมื่อรู้จำนวนรอบล่วงหน้า
- While Loop: ควบคุมด้วยเงื่อนไข (condition-controlled) เหมาะเมื่อไม่รู้จำนวนรอบล่วงหน้า
- For Loop มี update statement ในส่วนหัวลูป ส่วน While Loop มีแค่เงื่อนไข
- เงื่อนไขใน For Loop มักเป็นการเปรียบเทียบตัวเลข ส่วน While Loop ใช้ expression ใดๆ ที่ได้ค่า boolean
ตัวอย่างที่แสดงความแตกต่างกับ continue statement
For Loop กับ continue
#include <iostream>
using namespace std;
int main() {
cout << "For loop with continue:\n";
for (int i = 0; i < 5; i++) {
if (i == 3) continue;
cout << "loop count " << i << endl;
}
return 0;
}
For loop with continue: loop count 0 loop count 1 loop count 2 loop count 4
While Loop กับ continue (ระวัง infinite loop!)
#include <iostream>
using namespace std;
int main() {
cout << "While loop with continue:\n";
int i = 0;
while (i < 5) {
if (i == 3) continue; // i++ ไม่ได้รัน → infinite loop!
cout << "loop count " << i << endl;
i++;
}
return 0;
}
While loop with continue: loop count 0 loop count 1 loop count 2 (ค้างที่นี่ - infinite loop)
สรุป: ใน while loop หากมี continue ก่อน update statement จะทำให้ลูปไม่มีที่สิ้นสุด ส่วน for loop update statement อยู่ในหัวลูป จึงรันต่อได้ปกติ