Conditional Statements in C++ - if, else, and switch


Conditional statements are essential for controlling the flow of your C++ programs. They allow you to make decisions and execute different code blocks based on specific conditions. In this guide, we'll explore if statements, else statements, and switch statements in C++.


The if Statement

The if statement is used to execute a block of code if a specified condition is true. Here's the basic syntax:


if (condition) {
// Code to execute if the condition is true
}

Example:


#include <iostream>
using namespace std;
int main() {
int age = 20;
if (age >= 18) {
cout << "You are eligible to vote." << endl;
}
return 0;
}

In this code, the message "You are eligible to vote" is displayed because the condition age >= 18 is true.


The else Statement

The else statement is used in combination with if to execute a different block of code if the condition is false. Here's the syntax:


if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}

Example:


#include <iostream>
using namespace std;
int main() {
int age = 15;
if (age >= 18) {
cout << "You are eligible to vote." << endl;
} else {
cout << "You are not eligible to vote." << endl;
}
return 0;
}

In this code, the message "You are not eligible to vote" is displayed because the condition age >= 18 is false.


The switch Statement

The switch statement is used to select one of many code blocks to be executed. It's often used when you have multiple conditions to check. Here's the syntax:


switch (expression) {
case value1:
// Code to execute if expression matches value1
break;
case value2:
// Code to execute if expression matches value2
break;
// ...
default:
// Code to execute if expression doesn't match any case
}

Example:


#include <iostream>
using namespace std;
int main() {
int day = 3;
switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
default:
cout << "Unknown day" << endl;
}
return 0;
}

In this code, the output is "Wednesday" because day is set to 3, matching the case.


Conclusion

Conditional statements are fundamental for making decisions in C++ programs. They allow you to control the flow of your code based on specific conditions. As you continue your C++ journey, you'll discover more advanced uses and applications of these statements.