C++ If-Else

Concept about if-else statement.

If-Else:

In C++, the 'if-else' statement is used for decision-making. It allows you to execute a block of code if a particular condition is true, and another block if the condition is false. You can also nest 'if-else' statements to create more complex decision structures.

Here's a simple example of an 'if-else' statement:

cpp Copy Code
#include<iostream>

int main() {
    int number;

    std::cout << "Enter a number: ";
    std::cin >> number;

    if (number > 0) {
        std::cout << "The number is positive." << std::endl;
    } else {
        std::cout << "The number is non-positive." << std::endl;
    }

    return 0;
}
Output:
Enter a number: 1
The number is positive.

* In this example, if the entered number is greater than 0, it prints that the number is positive; otherwise, it prints that the number is non-positive.

Nested If-Else:

You can use nested if-else statements to create a series of conditions and execute different blocks of code based on those conditions. Now, let's look at an example of nested if-else statements:

cpp Copy Code
#include<iostream>

int main() {
    int x = 10;
    int y = 20;

    if (x > y) {
        std::cout << "x is greater than y" << std::endl;
    } else {

//nested if-else
        if (x < y) {
            std::cout << "x is less than y" << std::endl;
        } else {
            std::cout << "x is equal to y" << std::endl;
        }
    }
    return 0;
}

In this example, the outer if-else statement checks if 'x' is greater than 'y'. If true, it prints a message. If false, it enters the else block and checks if 'x' is less than 'y' in the inner if-else statement. If this is true, it prints a different message; otherwise, it prints another message indicating that 'x' is equal to 'y'.

Output:
x is less than y

Note: Remember that you can nest if-else statements to create more complex decision trees, but be mindful of code readability.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.