Home > Backend Development > C++ > body text

Explaining the else-if ladder statement in C

WBOY
Release: 2023-09-05 18:09:07
forward
1418 people have browsed it

This is the most general way to write multi-way decisions.

Syntax

Refer to the syntax given below -

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

Explaining the else-if ladder statement in C

##Algorithm

Refer to the algorithm given below −

START
Step 1: Declare int variables.
Step 2: Read a,b,c,d values at runtime
Step 3: i. if(a>b && a>c && a>d)
Print a is largest
ii.else if(b>c && b>a && b>d)
Print b is largest
iii. else if(c>d && c>a && c>b)
Print c is largest
iv. else
print d is largest
STOP
Copy after login

Example

The following is a C program that executes the Else If Ladder conditional operator−

Real-time demonstration

#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);
   }
}
Copy after login

Output

You will see the following output −

Run 1:Enter the values of a,b,c,d: 2 4 6 8
8 is the largest
Run 2: Enter the values of a,b,c,d: 23 12 56 23
56 is the largest
Copy after login

Consider another C program that uses else ifladder to display students’ grades-

Live Demonstration

#include<stdio.h>
int main(){
   int marks;
   printf("Enter the marks of a student:</p><p>");
   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;
}
Copy after login

Output

You will see the following output−

Run 1:
Enter the marks of a student:78
Grade=C
Run 2:
Enter the marks of a student:98
Grade=A
Copy after login

The above is the detailed content of Explaining the else-if ladder statement in C. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template