Decision Making Statements (if-else, switch) in C

In C programming language, decision making statements are used to execute different code blocks based on different conditions. Two commonly used decision making statements in C are the if-else statement and the switch statement.

1. if-else Statement: The if-else statement is used to execute a code block if a condition is true, and another code block if the condition is false. The syntax of the if-else statement is as follows:

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

Here’s an example of how to use the if-else statement in C:

#include 

int main() {
    int a = 10;

    if (a > 5) {
        printf("a is greater than 5\n");
    }
    else {
        printf("a is less than or equal to 5\n");
    }

    return 0;
}

In this example, we use the if-else statement to check if the value of variable a is greater than 5. If it is, we print “a is greater than 5”. If it is not, we print “a is less than or equal to 5”.

2. switch Statement: The switch statement is used to execute different code blocks based on different cases. The syntax of the switch statement is as follows:

switch (expression) {
    case constant1:
        // code to execute if expression is equal to constant1
        break;
    case constant2:
        // code to execute if expression is equal to constant2
        break;
    ...
    default:
        // code to execute if expression does not match any of the constants
}

Here’s an example of how to use the switch statement in C:

#include 

int main() {
    int day = 3;

    switch (day) {
        case 1:
            printf("Monday\n");
            break;
        case 2:
            printf("Tuesday\n");
            break;
        case 3:
            printf("Wednesday\n");
            break;
        case 4:
            printf("Thursday\n");
            break;
        case 5:
            printf("Friday\n");
            break;
        case 6:
            printf("Saturday\n");
            break;
        case 7:
            printf("Sunday\n");
            break;
        default:
            printf("Invalid day\n");
            break;
    }

    return 0;
}

In this example, we use the switch statement to print the name of the day of the week based on the value of variable day. If the value of day is 3, we print “Wednesday”. If the value of day is not any of the cases specified, we print “Invalid day”. Note that each case ends with a break statement, which is used to exit the switch statement after the code block for the matching case has been executed.