เรื่องที่ 9

คำสั่ง For

คำสั่ง for เป็นคำสั่งที่สั่งให้โปรแกรมทำงานซ้ำตามเงื่อนไขที่กำหนด โดยมีตัวอย่างการใช้งานดังนี้
for(ค่าเริ่มต้น; ประโยคเงื่อนไข; การเพิ่มค่าจากค่าเริ่มต้นไปยังค่าสิ้นสุด)
{
คำสั่ง;
}

ตัวอย่างโปรแกรมแสดงชื่อ-นามสกุลของตนเองจำนวน 10 ครั้ง
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i;
for(i=1; i<=10; i++)
{
printf(“Nattapon Buaurai\n”);
}
system(“pause”);
return 0;
}

ตัวอย่างโปรแกรมแสดงเลขคู่ตั้งแต่ 1 – 20
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i;
for(i=2; i<=20; i=i+2)
{
printf(“%d\n”,i);
}
system(“pause”);
return 0;
}

(ที่มา : http://www.nattapon.com/2014/01/c-language-10-/)