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

B10.โปรแกรมตรวจสอบเงื่อนไข (IF)

การเขียนโปรแกรมตรวจสอบเงื่อนไข (if) แบ่งออกเป็น 3 รูปแบบ คือ

1. if ( if ทางเดียว ) ไม่ตรงตามเงื่อนไขก็จะข้ามไป
if ("เงื่อนไข"){
//คำสั่งที่ต้องการทำ ; (statement)
}

ตัวอย่าง การเขียนโปรแกรมรับค่าอายุ
coding:
#include 
int main(void){
    int age;
    printf("How old are you = "); 
    scanf ("%d",&age); 
    if(age<18){ 
        printf("Your are young!\n"); 
    }
    printf("You are %d years old\n",age); 
    system("pause");
}
Output1:
How old are you = 5
Your are young!
You are 5 years old
Press any key to continue . . .
Output2:
How old are you = 20
You are 20 years old
Press any key to continue . . .

2. if – else (if สองทางเลือก) ต้องทำตามเงื่อนไขอย่างใดอย่างหนึ่งเสมอ
if ("เงื่อนไข"){ 
//คำสั่งที่ต้องการทำ ; (statement)
}else{
//คำสั่งที่ต้องการทำ ; (statement)
}
ตัวอย่าง การเขียนโปรแกรมตัดเกรด แบบสองเกรด ผ่านเป็น P ไม่ผ่าน เป็น F
#include 
int main(void){
    int score;
    printf("Enter your score = "); 
    scanf ("%d",&score); 
    if(score<50){ 
        printf("Grade = F\n"); 
    }else{
        printf("Grade = P\n"); 
    }
    system("pause");
}
Output1:
Enter your score = 45
Grade = F
Press any key to continue . . .
Output2:
Enter your score = 62
Grade = P
Press any key to continue . . .

3. if –else if (if มากกว่า 2 ทางเลือก) ไม่ตรงตามเงื่อนไขก็ตรวจสอบเงื่อนไขถัดไป
if ("เงื่อนไขที่ 1"){
//คำสั่งที่ต้องการทำ ; (statement)
}else if("เงื่อนไขที่ 2"){
//คำสั่งที่ต้องการทำ ; (statement)
}else{
//คำสั่งที่ต้องการทำ ; (statement)
}
ตัวอย่าง การเขียนโปรแกรมตัดเกรด 5 เกรด Coding:
#include 
int main(void){
    int score;
    printf("Enter score = "); 
    scanf ("%d",&score); 
    if(score>=0 && score<=49){ 
        printf("Grade = 0\n"); 
    }else if(score>=50 && score<=59){ 
        printf("Grade = 1\n"); 
    }else if(score>=60 && score<=69){ 
        printf("Grade = 2\n"); 
    }else if(score>=70 && score<=79){ 
        printf("Grade = 3\n"); 
    }else if(score>=80 && score<=100){ 
        printf("Grade = 4\n"); 
    }else{ 
        printf("Sory!.Enter Score[0-100]\n"); 
    }
    system("pause");
}
Output1:
Enter score = 50
Grade = 1
Press any key to continue . . .
Output2:
Enter score = 120
Sory!.Enter Score[0-100]
Press any key to continue . . .

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

Popular Posts