Introduction to C++ | if-else Statements

C++ if-else Statements

The if-else statement in C++ allows you to perform conditional checks. Based on the condition, it will execute one block of code if the condition is true, and a different block of code if the condition is false.

What is an if-else Statement?

The if-else statement evaluates a condition and executes one of two blocks of code:

Syntax:

Syntax of an if-else Statement


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

Example of if-else Statement

Here is an example that checks whether a number is positive or negative using the if-else statement:

Code Example


        #include <iostream>
        using namespace std;
        
        int main() {
            int number;
            cout << "Enter a number: ";
            cin >> number;
        
            // if-else statement to check if the number is positive or negative
            if (number >= 0) {
                cout << "The number is positive." << endl;
            } else {
                cout << "The number is negative." << endl;
            }
        
            return 0;
        }
                    

Output

Enter a number: -5
The number is negative.

Nested if-else

In some cases, you may want to check multiple conditions. This can be done using a nested if-else statement, where one if or else contains another if-else statement.

Example of a nested if-else statement:

Nested if-else Example


        #include <iostream>
        using namespace std;
        
        int main() {
            int number;
            cout << "Enter a number: ";
            cin >> number;
        
            // Nested if-else statement
            if (number > 0) {
                cout << "The number is positive." << endl;
            } else {
                if (number < 0) {
                    cout << "The number is negative." << endl;
                } else {
                    cout << "The number is zero." << endl;
                }
            }
        
            return 0;
        }
                    

Output

Enter a number: 0
The number is zero.

Pro Tip:

💡 Pro Tip

When using if-else statements, make sure that the condition is simple and clear. If you have multiple conditions to check, you can use logical operators like && (AND) and || (OR) to combine conditions into a single statement. For better readability, avoid deeply nested if-else statements whenever possible.