Table of Contents
The else-if ladder is used when a program needs to evaluate multiple conditions in sequence. Each if or else-if condition is evaluated from top to bottom until one condition evaluates to true.
Once a condition is satisfied, its associated block is executed and the remaining conditions in the ladder are skipped. If none of the conditions evaluate to true, the optional else block is executed.
Source Code #
#include <iostream>
int main()
{
int marks = 78;
if (marks >= 90)
{
std::cout << "Grade: A\n";
}
else if (marks >= 75)
{
std::cout << "Grade: B\n";
}
else if (marks >= 60)
{
std::cout << "Grade: C\n";
}
else
{
std::cout << "Grade: D\n";
}
return 0;
}
Output #
Grade: B
Explanation #
- The
ifstatement checks the first condition,marks >= 90. - If the first condition is
false, the firstelse ifcondition is evaluated. marks >= 75evaluates totruefor the value78.- Once a condition evaluates to
true, its corresponding block is executed. - The remaining
else ifandelseblocks are skipped after a matching condition is found. - The
elseblock executes only when none of the preceding conditions evaluate totrue. - Conditions in an
else-ifladder are evaluated from top to bottom. - The order of conditions can affect the result, so conditions should generally be arranged from the most restrictive to the least restrictive when using ranges.
return 0;terminates the program successfully.