Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

วิธีใช้คำสั่งเงื่อนไข 'else if ladder' ในภาษา C


Else-if ladder คือวิธีที่ทั่วไปที่สุดในการเขียนการตัดสินใจหลายทาง (Multi-way Decision)

ไวยากรณ์สำหรับ else-if ladder:

if (condition1)
    stmt1;
else if (condition2)
    stmt2;
    - - - - -
    - - - - -
else if (condition n)
    stmtn;
else
    stmt x;

แผนผังไหล (Flowchart)

อ้างอิงแผนผังด้านล่าง:

วิธีใช้คำสั่งเงื่อนไข  else if ladder  ในภาษา C

ตัวอย่าง

โปรแกรม C ใช้คำสั่งเงื่อนไข Else If Ladder:

#include <stdio.h>

void main() {
    int a, b, c, d;
    printf("Enter the values of a,b,c,d: ");
    scanf("%d%d%d%d", &a, &b, &c, &d);
    
    if(a > b) {
        printf("%d is the largest", a);
    } else if(b > c) {
        printf("%d is the largest", b);
    } else if(c > d) {
        printf("%d is the largest", c);
    } else {
        printf("%d is the largest", d);
    }
}

ผลลัพธ์

เมื่อรันโปรแกรม จะได้ผลลัพธ์ดังนี้:

Enter the values of a,b,c,d: 2 3 4 5
5 is the largest