If else in C++

The if-else statement is a fundamental control structure in C++ used to make decisions based on the evaluation of a condition. It allows the program to execute different blocks of code based on whether the condition is true or false.

The basic syntax of the if-else statement is as follows:

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

Here's a step-by-step breakdown of how the if-else statement works:

The condition in parentheses after the if keyword is evaluated. If the condition is true, the code inside the first block (enclosed in curly braces) is executed. If the condition is false, the code inside the else block is executed.

The else block is optional. If the condition is false and there is no else block, the program moves on to the next statement after the if-else statement.

Now, let's look at some detailed examples to illustrate the usage of if-else statements:

Example: Checking if a number is even or odd
#include<iostream>
using namespace std;
int main() {
    int number;
    cout << "Enter a number: ";
    cin >> number;
    if (number % 2 == 0) {
        cout << "The number is even." << endl;
    } else {
        cout << "The number is odd." << endl;
    }
    return 0;
}

Nested if-else

The if or else block can contain another if-else statement, allowing for multiple levels of decision-making.

Example
if (condition1) {
    // code block executed if condition1 is true
    if (condition2) {
        // code block executed if condition2 is true
    } else {
        // code block executed if condition2 is false
    }
} else {
    // code block executed if condition1 is false
}

Nested if-else statements can have more than two levels, depending on the complexity of the problem being solved.

if-else if-else ladder

This structure is used when there are multiple conditions to be checked, and only one of them should be executed.

Example
if (condition1) {
    // code block executed if condition1 is true
} else if (condition2) {
    // code block executed if condition1 is false and condition2 is true
} else if (condition3) {
    // code block executed if condition1 and condition2 are false and condition3 is true
} else {
    // code block executed if all conditions are false
}

The else if statements allow for sequential checking of conditions until a true condition is found or the final else block is reached.

Ternary operator

The ternary operator (?:) provides a compact way to write simple if-else statements.

Syntax
variable = (condition) ? expression1 : expression2;

If the condition is true, expression1 is evaluated and assigned to variable. If the condition is false, expression2 is evaluated and assigned to variable.

Example
int x = 10;
int y = (x > 5) ? 100 : 200;

In this example, if x is greater than 5, y is assigned the value 100; otherwise, it is assigned the value 200.