Zone Of Makos

Menu icon

Conditional Statements in C++

Conditional statements allow you to control the flow of execution in a program based on certain conditions. In C++, there are several types of conditional statements available, including if statements, if-else statements, and nested if statements. In this lesson, we will focus on if-related statements in C++.

The if Statement

The if statement is used to perform a certain action only if a specified condition is true. It has the following syntax:


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

The condition is an expression that evaluates to either true or false. If the condition is true, the code block inside the if statement is executed. Otherwise, the code block is skipped.

The if-else Statement

The if-else statement allows you to specify alternative actions to be performed based on the result of a condition. It has the following syntax:


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

If the condition in the if statement is true, the code block inside the if block is executed. If the condition is false, the code block inside the else block is executed instead.

Nested if Statements

You can also have if statements inside other if statements, creating nested if statements. This allows you to handle more complex conditions and multiple levels of branching. Here's an example:


if (condition1) {
    // Code to be executed if condition1 is true
    
    if (condition2) {
        // Code to be executed if both condition1 and condition2 are true
    }
}

Conclusion

In this lesson, we have covered the if statement, if-else statement, and nested if statements in C++. These conditional statements allow you to control the flow of your program based on specific conditions. However, it's important to note that there are more conditional constructs available in C++, such as the switch-case statement, which we will explore in the next lesson.