สำหรับลูป
for loop เป็นโครงสร้างควบคุมการทำซ้ำ มันรันคำสั่งจำนวนครั้งที่กำหนด อันดับแรก จะใช้ค่าเริ่มต้นจากจุดเริ่มต้นการวนซ้ำ ประการที่สอง ใช้เงื่อนไขซึ่งตรวจสอบจริงหรือเท็จ ในตอนท้ายจะเพิ่ม/ลดและอัปเดตตัวแปรลูป
นี่คือไวยากรณ์ของ for loop ในภาษา C
for ( init; condition; increment ) { statement(s); }
นี่คือตัวอย่าง for loop ในภาษา C
ตัวอย่าง
#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 loop ในภาษา C
while(condition) { statement(s); }
นี่คือตัวอย่าง while loop ในภาษา C
ตัวอย่าง
#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