Conditional statements: if, else, switch in C++

Conditional statements in C++ are used to execute different code blocks based on different conditions. Here are some of the most common conditional statements in C++:

1. if statement: The if statement is used to execute a block of code if a condition is true. If the condition is false, the code block is skipped. The basic syntax of the if statement is as follows:

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

For example:

int x = 10;
if (x > 0) {
    cout << "x is positive" << endl;
}

2. if-else statement: The if-else statement is used to execute one block of code if a condition is true, and a different block of code if the condition is false. The basic syntax of the if-else statement is as follows:

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

For example:

int x = -10;
if (x > 0) {
    cout << "x is positive" << endl;
} else {
    cout << "x is non-positive" << endl;
}

3. else-if statement: The else-if statement is used to check multiple conditions and execute different code blocks based on the conditions. The basic syntax of the else-if statement is as follows:

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 all conditions are false
}

For example:

int x = 0;
if (x > 0) {
    cout << "x is positive" << endl;
} else if (x < 0) {
    cout << "x is negative" << endl;
} else {
    cout << "x is zero" << endl;
}

4. switch statement: The switch statement is used to execute different code blocks based on the value of a variable or expression. The basic syntax of the switch statement is as follows:

switch (expression) {
    case value1:
        // code to be executed if expression equals value1
        break;
    case value2:
        // code to be executed if expression equals value2
        break;
    // more cases can be added here
    default:
        // code to be executed if expression does not equal any of the above values
        break;
}

For example:

int day = 3;
switch (day) {
    case 1:
        cout << "Monday" << endl;
        break;
    case 2:
        cout << "Tuesday" << endl;
        break;
    case 3:
cout << "Wednesday" << endl;
        break;
    case 4:
        cout << "Thursday" << endl;
        break;
    case 5:
        cout << "Friday" << endl;
        break;
    default:
        cout << "Weekend" << endl;
        break;
}

In the switch statement, the code block associated with the matching case is executed, and the break statement is used to exit the switch statement. If none of the cases match, the default code block is executed.

These are some of the most common conditional statements in C++. Understanding how to use these statements is an important part of learning C++.