• Home
  • 4.4 else-if Ladder

4.4 else-if Ladder

View Categories

4.4 else-if Ladder

1 min read

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 if statement checks the first condition, marks >= 90.
  • If the first condition is false, the first else if condition is evaluated.
  • marks >= 75 evaluates to true for the value 78.
  • Once a condition evaluates to true, its corresponding block is executed.
  • The remaining else if and else blocks are skipped after a matching condition is found.
  • The else block executes only when none of the preceding conditions evaluate to true.
  • Conditions in an else-if ladder 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.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *