Conditional Statements in C++
Introduction
Conditional statements are fundamental to programming languages. They allow a program to execute certain pieces of code based on specific conditions. In C++, the main conditional statements include if, else if, else, and switch. Understanding these structures is essential for controlling the flow of a program.
If Statement
The if statement executes a block of code if a specified condition is true. If the condition is false, the block of code inside the if statement is skipped.
Example:
if (condition) {
// code to be executed if condition is true
}
Here is a practical example in C++:
Example:
#include <iostream>
int main() {
int number = 10;
if (number > 5) {
std::cout << "Number is greater than 5" << std::endl;
}
return 0;
}
Output:
Number is greater than 5
If-Else Statement
The if-else statement provides an alternative block of code to execute if the condition is false.
Example:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Here is a practical example in C++:
Example:
#include <iostream>
int main() {
int number = 3;
if (number > 5) {
std::cout << "Number is greater than 5" << std::endl;
} else {
std::cout << "Number is not greater than 5" << std::endl;
}
return 0;
}
Output:
Number is not greater than 5
Else If Statement
The else if statement allows you to check multiple conditions.
Example:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if both conditions are false
}
Here is a practical example in C++:
Example:
#include <iostream>
int main() {
int number = 5;
if (number > 10) {
std::cout << "Number is greater than 10" << std::endl;
} else if (number > 5) {
std::cout << "Number is greater than 5" << std::endl;
} else {
std::cout << "Number is 5 or less" << std::endl;
}
return 0;
}
Output:
Number is 5 or less
Switch Statement
The switch statement allows a variable to be tested for equality against a list of values, each with its own block of code.
Example:
switch (variable) {
case value1:
// code to be executed if variable equals value1
break;
case value2:
// code to be executed if variable equals value2
break;
default:
// code to be executed if variable does not equal any value
}
Here is a practical example in C++:
Example:
#include <iostream>
int main() {
int day = 3;
switch (day) {
case 1:
std::cout << "Monday" << std::endl;
break;
case 2:
std::cout << "Tuesday" << std::endl;
break;
case 3:
std::cout << "Wednesday" << std::endl;
break;
default:
std::cout << "Invalid day" << std::endl;
}
return 0;
}
Output:
Wednesday
Conclusion
Conditional statements are crucial for decision-making in programming. They allow a program to execute different code blocks based on specific conditions. Mastering conditional statements is essential for creating dynamic and responsive programs in C++.
