else-if statement in C++

In our previous lessons, we learned how to make a single choice using if and else. But what if life gives you more than two options? In this lecture, we explore Multiple Selection using the else-if ladder, allowing your program to navigate complex decisions efficiently.

Definitions

Before we dive into the logic, let’s define the essential terms:

Topic Simple Definition
Multiple Selection A programming structure used to handle many different conditions at once.
else-if Statement A command that checks a new condition only if the previous conditions were false.
Sequential Checking The process where the computer checks conditions one by one from top to bottom.
Mutually Exclusive A rule stating that only one block of code in the ladder will run, even if multiple could be true.
Default Branch (else) The final “catch-all” block that runs if none of the specific conditions are met.

 

Explanation

The else-if statement (often called an else-if ladder) is a multiple selection structure used to evaluate several different conditions in a specific sequence.
We use it for several reasons:
  • Handling Multiple Outcomes: Unlike a basic if-else which only handles two paths, else-if allows a program to deal with many different conditions at once.
  • Sequential Efficiency: The computer checks conditions from top to bottom; as soon as it finds one that is True, it executes that block and skips all remaining conditions in the ladder.
  • Providing a Default: It typically ends with an else block, which acts as a “catch-all” or default branch if none of the specific conditions are met.
A classic example is a grading system, where the program checks if marks are above 90 (A+), then 80 (A), then 70 (B), and so on, until it finds the correct range
  1. The Real-Life Logic of Decisions

Imagine a student named Ali deciding his day based on the weather.

  • If it is raining, he will study.
  • Else if it is sunny, he will go for a walk.
  • Else if it is cloudy, he will meet friends.
  • Else (if none of the above), he will just sleep.

This is exactly how C++ handles multiple selections. The program doesn’t do everything; it picks the first path that matches the current situation and skips the rest.

  1. How the Compiler Processes the “Ladder”

The else-if ladder works in a specific sequence:

  1. It checks the first if. If true, it runs that block and stops.
  2. If the first if is false, it moves to the first else-if.
  3. This continues down the ladder until a “True” is found or it hits the final else.
  4. Once any block executes, the rest of the ladder is completely skipped.
  1. Syntax Rules

    if (condition1) {// Runs if  condition1 is true

    } else if(condition2) {

    // Runs if condition2 is true

    }else if(condition3) {

    // Runs if condition3 is true

    }
    .
    .
    .
    .
    else{
    //Runs if all conditions are false

    }
    Extra Tips:

  • Braces { }: If a block contains multiple statements, you must use braces. For single lines, they are optional but recommended for clarity.
  • The Final else: This is your safety net. Use it to handle invalid data or unexpected inputs.

Example 1: The Student Grading System

This program assigns a grade based on marks entered by the user.

Description: The program takes an integer input (0-100) and checks it against multiple ranges. If marks are 90+, it’s an A+. If they are 80-89, it’s an A, and so on.

# include <iostream>
using namespace std;
int main(){
    int marks=0;
    cout<<"Please enter obtained marks: ";
    cin>>marks;
    if (marks >= 90) {
        cout << "Grade: A+";
    } 
    else if (marks >= 80) {
        cout << "Grade: A";
    }
    else if (marks >= 70) {
        cout << "Grade: B";
    } 
    else {
        cout << "Grade: F";
    }
    return 0;
}

Example 2: The Weather Decision Bot

Based on Ali’s daily routine, this program decides an activity.

Description: This uses a character or integer code to represent weather states and outputs the corresponding activity.

# include <iostream>
using namespace std;
int main(){
    char weather;
    cout<<"Ali! Please enter the weather condition!\nR: Rainy \nS: Sunny \nC: Cloudy"
    if (weather == 'R') { // R for Rain
         cout << "Activity: Study";
    } 
    else if (weather == 'S') { // S for Sunny
         cout << "Activity: Sleep";
    } 
    else if(weater == 'C') { //C for Cloudy
         cout << "Activity: Walk";
    }
    else{
         cout<<"Invalid Input!"
    }
    return 0;
}

Example 3: Number Classifier

Description: A simple program to determine if a number is positive, negative, or zero. This demonstrates how to handle a limited set of possibilities perfectly.

# include <iostream>
using namespace std;
int main(){
       int num=0;
       cout<<"Enter any number: ";
       cin>>num;
       if (num > 0) {
                 cout << "The number is Positive";
       } 
       else if (num < 0) {
                cout << "The number is Negative";
       } 
       else {
               cout << "The number is Zero";
       }  
       return 0;
}

Try It Yourself Challenges:

  1. The “Invalid” Test: In Example 1, what happens if a user enters -1? How can you modify the else block to print “Invalid Marks”?
  2. Logic Order: What would happen if you put else if (marks >= 50) before if (marks >= 90)? Try to trace it! (Hint: The program stops at the first “True” it finds).
  3. A Mini Calculator: Try building a “Calculator” that asks for two numbers and an operation (+, -, *, /) using else-if.

Point to Ponder: Why is it more efficient to use an else-if ladder rather than five separate if statements? (Hint: Think about how many times the computer has to “check” a condition).

Conclusion & Next Steps

Multiple selection is the backbone of complex software logic, thats why else-if statement is crucial, as it is used in every program where a decision has to be made among multiple choices. For a deep dive into more advanced features, visit the official C++ documentation.

Engagement Boost: What’s your biggest C++ fear—logical errors in your “ladder” or just forgetting a closing brace? Let us know in the comments!