Lesson 4
Mastering Control Structures with If, Else, and Switch Statements
Introduction

Welcome! Today, we are unraveling the crucial aspects of C++ control structures, specifically the if, else, and switch statements. Control structures steer the flow of your program based on conditions, which is similar to decision-making in daily life. Fascinating, isn't it? Let's dive right in.

The anatomy of the `if` statement

The if statement checks a given condition inside parentheses, which must result in a boolean value (true or false):

C++
1if (condition) { 2 // Code to be executed if the condition is true 3}
  • The condition is placed between the parentheses ().
  • If the condition evaluates to true, the code block within the curly braces {} executes.
  • This block will not run if the condition is false.
`if` Statement in action

Consider a scenario at a restaurant. When you are hungry, you order food. This situation can be modeled in C++ using the if statement, as illustrated below:

C++
1#include <iostream> 2 3int main() { 4 bool isHungry = true; 5 6 if (isHungry) { 7 //The following line will only be executed if isHungry is true 8 std::cout << "Order food!"; 9 } 10 11 return 0; 12}

The if statement checks the condition: isHungry. If it's true, the statement within the block is executed. In this case, it prints "Order food!".

Digging Deeper into `if-else` Structures

The if-else statement in C++ tests a condition, then executes a certain task if the condition is met and performs a different task if not fulfilled. For instance, in a restaurant, you have a choice between the special dish or a juice, based on whether you're hungry or not:

C++
1#include <iostream> 2 3int main() { 4 bool isHungry = false; 5 6 if (isHungry) { 7 //Executed when isHungry is true 8 std::cout << "Order the special dish!"; 9 } else { 10 //Executed when isHungry is false 11 std::cout << "Just order a juice."; 12 } 13 14 return 0; 15}
Exploring Comparison Operators within Control Structures

Before diving deeper into control structures, it’s essential to understand the role of comparison operators. These operators allow us to compare two values, resulting in a boolean value (true or false). This outcome determines the flow of control structures like if, else if, and switch.

Here are the most commonly used comparison operators in C++:

  • == checks if two values are equal.
  • != checks if two values are not equal.
  • > checks if the left value is greater than the right.
  • < checks if the left value is less than the right.
  • >= checks if the left value is greater than or equal to the right.
  • <= checks if the left value is less than or equal to the right.
Comparison Operators in Action

Imagine you are building an application that assigns tasks based on the priority levels. Tasks with a priority level higher than 5 need immediate attention, whereas tasks with a priority less than or equal to 5 can be scheduled for later. Here's how you can utilize the comparison operators:

C++
1#include <iostream> 2 3int main() { 4 int taskPriority = 6; 5 6 if (taskPriority > 5) { 7 std::cout << "This task needs immediate attention!"; 8 } else { 9 std::cout << "This task can be scheduled for later."; 10 } 11 12 return 0; 13} // "This task needs immediate attention!" will be printed

The above code effectively demonstrates how comparison operators are used within the if-else statement to make decisions based on the given conditions.

Understanding and utilizing comparison operators are fundamental in controlling the flow of your programs, ensuring you create efficient and effective C++ applications.

Looking at Multiple Conditions Using `else if`

An else if statement is useful when handling more than two possibilities. Imagine visiting an amusement park where the ride choices depend on your age. For children under 10, it's the merry-go-round; for those aged 10 to 18, the roller coaster is the thrill, and for adults, the horror house awaits. Let's see this in action:

C++
1#include <iostream> 2 3int main() { 4 int age = 15; 5 6 if (age < 10) { 7 std::cout << "Head to the merry-go-round!"; 8 } else if (age <= 18) { 9 std::cout << "Time for the roller coaster!"; // This will be executed when age is between 10 and 18 10 } else { 11 std::cout << "Dare the horror house!"; 12 } 13 14 return 0; 15}
Understanding the `switch` Statement

The switch statement evaluates an expression once and compares its value against a list of case values. It executes a set of statements associated with that case. It's an efficient alternative to a long series of if-else statements when dealing with conditions based on a single variable.

C++
1#include <iostream> 2 3int main() { 4 int dayOfWeek = 5; // let's assume it's a Friday 5 6 switch(dayOfWeek) { 7 case 1: // If dayOfWeek is 1, 8 case 2: // or 2, 3, 4, 5 9 case 3: 10 case 4: 11 case 5: // then this code executes. 12 std::cout << "Work, work, work!"; // Prints message for weekdays. 13 break; // Exits the switch situation. 14 case 6: // If dayOfWeek is 6, 15 case 7: // or 7, 16 std::cout << "Relax and chill!"; // Prints message for weekends. 17 break; // Prevents fall-through. 18 default: // If none of the above cases are true, 19 std::cout << "Invalid day!"; // this executes. 20 } 21 22 return 0; 23} // "Work, work, work!" will be printed

A case value is one of the possible values the switch expression (dayOfWeek in our case) can have. When the value of dayOfWeek matches a case, the code block following that case executes.

A break statement ends the execution within the switch construct. Without break, execution flows into the next case block (this is known as fall-through), which may lead to unexpected behaviors. In our scenario, after printing "Work, work, work!" for a weekday, break ensures the program exits the switch statement and does not unintentionally execute the weekend case or the default case.

The default case executes if none of the case values match the switch expression value. In this example, default: catches any dayOfWeek value outside 1 through 7, displaying "Invalid day!" as feedback.

Lesson Summary, Real-world Applications, and Practice

Terrific work! You've mastered the control structures in C++, namely, if, else, else if, and switch. These fundamental concepts are widely applicable in real-world situations like branching execution based on user input or implementing complex decision trees.

Head over to the exercise section to reinforce your understanding of these concepts. Remember, practice is the key to developing your programming skills. Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.