C Switch

Used for multi-way branching alternative to if-else.
it allows to choose one from multiple code blocks based on the value of an expression.

Syntax
switch (expression) {
case constant1:
// Code to be executed if expression matches constant1
break;

case constant2:
// Code to be executed if expression matches constant2
break;

// Additional cases as needed

default:
// Code to be executed if none of the cases match
}

Example
#include <stdio.h>

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");
    }

    return 0;
}

The switch statement evaluates the value of the day variable.
By giving the value of day the case block is executed.
if no value is matched to the case value then the default block is executed.
THe break statement is used to prevent execution of next case.


Quick Recap - Topics Covered

C Switch

Practice With Examples in Compilers

The Concepts and codes you leart practice in Compilers till you are confident of doing on your own. A Various methods of examples, concepts, codes availble in our websites. Don't know where to start Down some code examples are given for this page topic use the code and compiler.


Example 1
Example 1 Example 2 Example 3 Example 4 Example 5


Quiz


FEEDBACK