Understanding if-else Statements in C++ for Beginners

  • Last updated Apr 25, 2024

In C++, the if-else statement is used for conditional execution of code. It allows you to specify two blocks of code, one to be executed if a certain condition is true (the if block), and another to be executed if the condition is false (the else block).

Here is the basic syntax of the if-else statement in C++:

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

Here's a simple example that demonstrates the use of the if-else statement in C++:

#include <iostream>

int main() {
    int number = 20;

    if (number > 15) {
        std::cout << "Number is greater than 15." << std::endl;
    } else {
        std::cout << "Number is not greater than 15." << std::endl;
    }

    return 0;
}

In this example, the condition (number > 15) is evaluated. Since number is 20, which is indeed greater than 15, the code inside the if block is executed, and it prints "Number is greater than 15".

If the condition is false, the code inside the else block will be executed instead.

You can also use if-else if-else statements for multiple conditions:

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 no conditions are true
}

Remember that proper indentation is essential for readability, and the conditions should evaluate to either true or false for the code to work as expected.