Khác - nếu bậc thang là cách viết chung nhất để viết một quyết định nhiều chiều.
Cú pháp cho else if Ladder như sau -
if (condition1) stmt1; else if (condition2) stmt2; - - - - - - - - - - else if (condition n) stmtn; else stmt x;
Lưu đồ
Tham khảo sơ đồ dưới đây -
Ví dụ
Sau đây là chương trình C để thực hiện câu lệnh điều kiện 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);
}
} Đầu ra
Khi chương trình trên được thực thi, nó tạo ra kết quả sau -
Enter the values of a,b,c,d: 2 3 4 5 5 is the largest