这是编写多路决策的最通用方法。
语法请参阅下面给出的语法 -
if (condition1)stmt1;else if (condition2)stmt2;- - - - -- - - - -else if (condition n)stmtn;elsestmt x;
算法参考下面给出的算法 −
startstep 1: declare int variables.step 2: read a,b,c,d values at runtimestep 3: i. if(a>b && a>c && a>d)print a is largestii.else if(b>c && b>a && b>d)print b is largestiii. else if(c>d && c>a && c>b)print c is largestiv. elseprint d is largeststop
示例以下是执行else if ladder条件运算符的c程序 −
实时演示
#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 && a>c && a>d){ printf("%d is the largest",a); }else if(b>c && b>a && b>d){ printf("%d is the largest",b); }else if(c>d && c>a && c>b){ printf("%d is the largest",c); }else{ printf("%d is the largest",d); }}
输出您将看到以下输出 −
run 1:enter the values of a,b,c,d: 2 4 6 88 is the largestrun 2: enter the values of a,b,c,d: 23 12 56 2356 is the largest
考虑另一个 c 程序,它使用 else ifladder 显示学生的成绩 -
实时演示
#include<stdio.h>int main(){ int marks; printf("enter the marks of a student:
"); scanf("%d",&marks); if(marks <=100 && marks >= 90) printf("grade=a"); else if(marks < 90 && marks>= 80) printf("grade=b"); else if(marks < 80 && marks >= 70) printf("grade=c"); else if(marks < 70 && marks >= 60) printf("grade=d"); else if(marks < 60 && marks > 50) printf("grade=e"); else if(marks == 50) printf("grade=f"); else if(marks < 50 && marks >= 0) printf("fail"); else printf("enter a valid score between 0 and 100"); return 0;}
输出您将看到以下输出 −
run 1:enter the marks of a student:78grade=crun 2:enter the marks of a student:98grade=a
以上就是在c语言中解释else-if梯形语句的详细内容。