For Loop
ลูป for ใช้เมื่อทราบจำนวนรอบการทำงานล่วงหน้า ประกอบด้วย 3 ส่วน: ค่าเริ่มต้น, เงื่อนไข, และการเพิ่ม/ลดค่า
รูปแบบไวยากรณ์
for (init; condition; increment) {
statement(s);
}ตัวอย่าง
#include <stdio.h>
int main() {
int a = 5;
for (int i = 0; i <= 5; i++) {
printf("Value of a: %d\n", a);
a++;
}
return 0;
}ผลลัพธ์
Value of a: 5 Value of a: 6 Value of a: 7 Value of a: 8 Value of a: 9 Value of a: 10
While Loop
ลูป while ใช้เมื่อไม่ทราบจำนวนรอบล่วงหน้า ทำงานต่อไปจนกว่าเงื่อนไขจะเป็นเท็จ
รูปแบบไวยากรณ์
while (condition) {
statement(s);
}ตัวอย่าง
#include <stdio.h>
int main() {
int a = 5;
while (a < 10) {
printf("Value of a: %d\n", a);
a++;
}
return 0;
}ผลลัพธ์
Value of a: 5 Value of a: 6 Value of a: 7 Value of a: 8 Value of a: 9