else if Ladder
The else...if Clause
So far, we've learned about if and else statements, which help us make decisions in our programs. But what if we have more than two possible outcomes for a condition? This is where the else if statement comes in. It allows us to check multiple conditions one by one and execute different code blocks based on the first condition that evaluates to true. Let's explore why this is important.
Example Problem - Grading Students:
Imagine we are writing a program to grade students based on their scores. We want to categorize them into four grades: A, B, C, and D, depending on their score. Here's the problem:
- If a student's score is 90 or above, they get an "A."
- If the score is between 80 and 89, they get a "B."
- If the score is between 70 and 79, they get a "C."
- If the score is between 60 and 69, they get a "D."
- If the score is below 60, they fail and get an "F."
Now, let's write a program to solve this problem and see why we need else if statements.
#include <iostream>
using namespace std;
int main() {
int score;
cout << "Enter your score: ";
cin >> score;
if (score >= 90) {
cout << "WOW! Congratulations, you've earned an A+!";
} else if (score >= 80) {
cout << "GREAT JOB! You've scored a solid B.";
} else if (score >= 70) {
cout << "NICE WORK! You've achieved a respectable C.";
} else if (score >= 60) {
cout << "KEEP IT UP! You've secured a passing grade of D.";
} else {
cout << "DON'T GIVE UP! You'll bounce back stronger next time. (F)";
}
return 0;
}
Now, let's answer a few common questions that you might have here:
- Why do we use else if for the intermediate conditions (B, C, and D)?
Good question! Using else if ensures that if one condition is true (e.g., score is 85, so they get a B), the other conditions (C and D) are not checked. This makes our program more efficient and prevents multiple grades for one student. - Why is there an else at the end?
The else at the end is like a backup plan. If none of the previous conditions are true, the student is considered to have failed and gets an "F."
Sequential Evaluation - Like a Restaurant Menu:
Think of "else if" statements as going through a restaurant menu to pick your favorite dish (say ,dosa). The menu lists multiple options (conditions), and your goal is to find dosa.
Our menu is the list of "else if" conditions. Each condition is like a different dish on the menu, waiting for you to decide. The program, just like you at the restaurant, starts at the top of the menu and checks each condition one by one.
You begin at the top of the menu and check the first dish (condition). If it's not what you want (dosa in this case), you move to the next one.
As soon as you see the dish you've been craving (dosa), you don't bother looking at the other dishes because you've found what you want. The program works the same way. It stops checking conditions as soon as it finds the first one that's true.
Time to Eat:
Just like when you finally discover your favorite dish on the menu and order it, the program immediately starts executing the associated code. It's like your food arriving at the table, and you dig in.
Now, let's see this in code with a simple example:
#include <iostream>
using namespace std;
int main() {
int time = 15;
if (time < 12) {
cout << "Good morning!" << endl;
} else if (time < 18) {
cout << "Good afternoon!" << endl;
} else {
cout << "Good evening!" << endl;
}
return 0;
}
Output:
In this code, we're checking the time of day and saying "Good morning," "Good afternoon," or "Good evening" based on the time. The program will stop checking conditions as soon as it finds the first one that's true, and it will print the corresponding greeting and won't check the later conditions. So, it's like picking your favorite dish from the menu and enjoying your meal without bothering with the rest of the menu. 😊🍽️
What if we used if statements instead of else if statements?
If we used if statements for the above code, shown as below:
#include <iostream>
using namespace std;
int main() {
int time = 15;
if (time < 12) {
cout << "Good morning!" << endl;
}
if (time < 18) {
cout << "Good afternoon!" << endl;
}
if (time >= 18) {
cout << "Good evening!" << endl;
}
return 0;
}
In this way, the output printed will still be the same, but it's a little inefficient, because all the if statements are going to check their respective conditions, unlike else if ladder, where the later else ifs are not checked once the condition is met.
For ex - for the above code, the time is 15. Execution takes place as:
- First if will check if time < 12, it's not so it will not execute the commands inside.
- Now second if will check if time < 18, it is, so it will execute the commands inside.
- Now the third if statement will check if time >= 18, it is not, hence will not execute the commands inside. If we used else if ladder instead of ifs, the later conditions (to the condition where it was true) wouldn't be checked.
So this is the difference between using if statements and else if ladder.
Problems
Sorting Numbers
You have three distinct integer numbers: `num1, num2, and num3. Write a C++ program to determine and display which number is the largest, the second largest, and the smallest among the three.
C++ Code
#include <iostream>
using namespace std;
int main() {
int num1, num2, num3;
// Input: Ask the user to enter three numbers
cout << "Enter the first number: ";
cin >> num1;
cout << "Enter the second number: ";
cin >> num2;
cout << "Enter the third number: ";
cin >> num3;
// Find the largest, second largest, and smallest numbers
int largest, secondLargest, smallest;
if (num1 > num2 && num1 > num3) {
largest = num1;
if (num2 > num3) {
secondLargest = num2;
smallest = num3;
} else {
secondLargest = num3;
smallest = num2;
}
} else if (num2 > num1 && num2 > num3) {
largest = num2;
if (num1 > num3) {
secondLargest = num1;
smallest = num3;
} else {
secondLargest = num3;
smallest = num1;
}
} else {
largest = num3;
if (num1 > num2) {
secondLargest = num1;
smallest = num2;
} else {
secondLargest = num2;
smallest = num1;
}
}
// Output: Display the results
cout << "Largest: " << largest << endl;
cout << "Second Largest: " << secondLargest << endl;
cout << "Smallest: " << smallest << endl;
return 0;
}
Ticket Pricing in Rupees
You are developing a simple program for a movie theater in India. The theater has different ticket prices based on the age of the moviegoers. Here are the pricing rules in Indian Rupees (₹):
- Children (age 12 and below) pay ₹100 per ticket.
- Adults (age 13 to 64) pay ₹200 per ticket.
- Seniors (age 65 and above) pay ₹150 per ticket.
Write a C++ program that takes the age of a moviegoer as input and calculates the ticket price they should pay in Indian Rupees (₹).
C++ Code
#include <iostream>
using namespace std;
int main() {
int age;
double ticketPrice;
// Input: Ask the user to enter the age
cout << "Enter the age of the moviegoer: ";
cin >> age;
// Use if, else if, and else statements to calculate the ticket price in Indian Rupees (₹)
if (age <= 12) {
ticketPrice = 100.0; // Children pay ₹100
} else if (age >= 13 && age <= 64) {
ticketPrice = 200.0; // Adults pay ₹200
} else {
ticketPrice = 150.0; // Seniors pay ₹150
}
// Output: Display the calculated ticket price in Indian Rupees (₹)
cout << "Ticket price: ₹" << ticketPrice << endl;
return 0;
}
Summary
- The if statement helps us make choices in our code. When a certain condition is true, we do something.
- If there's an "else" part, we do something different when the if-condition is false.
- If we have more choices, we can use "else if" to add them.
As you finish this else if journey, more exciting coding adventures are just around the corner! 🚀💻 Get ready for more fun and learning ahead