วันอาทิตย์ที่ 12 กันยายน พ.ศ. 2553

B11.โปรแกรมแบบทำซ้ำ(Loop)

การทำซ้ำ (Loop) คือการช่วยลดการเขียนคำสั่งซ้ำๆ กันของโปรแกรมเมอร์ แบ่งออกเป็น 3 รูปแบบ ดังนี้
1. for คือ การทำซ้ำจนกว่าเงื่อนไขจะเป็นเท็จ
for("กำหนดค่าเริ่มต้น";"เงื่อนไขในการตรวจสอบ";"ตัวแปรที่เปลี่ยนแปลง"){
//คำสั่งที่ต้องการทำ ; (statement)
}
ตัวอย่าง
Coding:
#include 
int main(void){
    int i;
    for(i=0;i<=4;i++){
        printf("C Programming\n");
    }
    system("pause");
}
Output:
C Programming
C Programming
C Programming
C Programming
C Programming
Press any key to continue . . .
2. while คือ เหมือนกับ for Loop
"กำหนดค่าเริ่มต้น" ; 
while ("เงื่อนไขในการตรวจสอบ"){
//คำสั่งที่ต้องการทำ ; (statement)
//.
//.
"ตัวแปรที่ต้องการเปลี่ยนแปลง" ;
}
ตัวอย่าง Coding:
#include 
int main(void){
    int i;
    i=0;
    while(i<=4){
        printf("C Programming\n");
        i++;
    }
    system("pause");
}
Output:
C Programming
C Programming
C Programming
C Programming
C Programming
Press any key to continue . . .
3. do..while คือ การทำซ้ำจนกว่าเงื่อนไขจะเป็นเท็จ (ต่างตรงที่ do..while ทำไปก่อนอย่างน้อย 1 รอบการทำงานเสมอ แล้วค่อยไปตรวจสอบเงื่อนไข
"กำหนดค่าเริ่มต้น" ; 
do{
//คำสั่งที่ต้องการทำ ; (statement)
//.
//.
"ตัวแปรที่ต้องการเปลี่ยนแปลง" ;
}while ("เงื่อนไขในการตรวจสอบ");
ตัวอย่าง Coding:
#include 
int main(void){
    int i;
    i=0;
    do{
        printf("C Programming\n");
        i++;
    }while(i<=4);
    system("pause");
}
Output:
C Programming
C Programming
C Programming
C Programming
C Programming
Press any key to continue . . .

ไม่มีความคิดเห็น:

Popular Posts