Conditional statements are an essential part of any programming language, and C++ is no exception. In C++, conditional statements such as if and else allow you to control the flow of your program based on certain conditions. In this guide, we’ll explore the basics of if and else statements in C++, including syntax, examples, and common use cases.
What are if and else statements in C++?
Conditional statements in C++ are used to execute code based on certain conditions. The most common conditional statements in C++ are if and else. The if statement is used to execute a block of code if a specified condition is true. The else statement is used to execute a block of code if the condition specified in the if statement is false.
Syntax of if and else statements in C++
The basic syntax of an if statement in C++ is as follows:
if (condition) {
// Code to execute if condition is true
}
The condition can be any expression that can be evaluated to true or false, such as a boolean expression or a comparison expression.
The syntax for the if-else statement in C++ is as follows:
if (condition) {
// code to execute if the condition is true
}
else {
// code to execute if the condition is false
}
The else block is optional, but if it is present, then it contains the code to be executed if the condition in the if block is false.
Examples: Let’s look at some examples of using if and else statements in C++.
Example 1:
The condition can be any valid expression that returns a Boolean value. For example, you might check if a variable is equal to a certain value, like this:
int x = 5;
if (x == 5) {
std::cout 5) {
cout = 90) {
std::cout = 80) {
Nested if-else statements
Sometimes, it’s necessary to evaluate multiple conditions, and one way to do that is to use nested if-else statements. Nested if-else statements are simply if-else statements within other if-else statements.
if(condition1) {
// code block to be executed if condition1 is true
if(condition2) {
// code block to be executed if both condition1 and condition2 are true
}
else {
// code block to be executed if condition1 is true but condition2 is false
}
}
else {
// code block to be executed if condition1 is false
}
Here’s an example:
#include
using namespace std;
int main() {
int x = 10, y = 5;
if (x == 10) {
if (y == 5) {
cout