C++ If else

In C++ programming, if statements are fundamental for decision-making. They allow the program to execute different code blocks based on whether a condition evaluates to true or false. Understanding and using different types of if statements can help control the flow of a program and implement complex logic. Here’s a breakdown of the various types of if statements in C++:

1. if Statement

The basic form of an if statement evaluates a condition and executes a block of code if the condition is true.

Syntax:

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

Example:

#include <iostream>

int main() {
    int age = 18;
    if (age >= 18) {
        std::cout << "You are an adult." << std::endl;
    }
}

Output:

You are an adult.

2. if-else Statement

The if-else statement provides an alternative set of instructions if the condition evaluates to false.

Syntax:

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

Example:

#include <iostream>

int main() {
    int age = 16;
    if (age >= 18) {
        std::cout << "You are an adult." << std::endl;
    } else {
        std::cout << "You are not an adult." << std::endl;
    }
    return 0;
}

Output:

You are not an adult.

3. Nested if Statements

Nested if statements are used when you need to check multiple conditions. An if statement can contain other if statements within its block.

Syntax:

if (condition1) {
if (condition2) {
// Code to execute if both conditions are true
} else {
// Code to execute if condition1 is true but condition2 is false
}
} else {
// Code to execute if condition1 is false
}

Example:

#include <iostream>

int main() {
    int age = 20;
    bool hasID = true;

    if (age >= 18) {
        if (hasID) {
            std::cout << "You can enter the club." << std::endl;
        } else {
            std::cout << "ID required to enter the club." << std::endl;
        }
    } else {
        std::cout << "You are not old enough to enter the club." << std::endl;
    }

    return 0;
}

Output:

You can enter the club.

4. if-else-if Ladder

An if-else-if ladder is used to evaluate multiple conditions sequentially. It allows more than two possible outcomes by adding additional else if blocks.

Syntax:

if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else if (condition3) {
// Code to execute if condition3 is true
} else {
// Code to execute if none of the above conditions are true
}

Example:

#include <iostream>

using namespace std;

int main() {
    int score = 85;

    if (score >= 90) {
        cout << "Grade: A" << endl;
    } else if (score >= 80) {
        cout << "Grade: B" << endl;
    } else if (score >= 70) {
        cout << "Grade: C" << endl;
    } else {
        cout << "Grade: D" << endl;
    }

    return 0;
}

Output:

Grade: B