Switch case in C programming

Switch case is a conditional control statement that allows us to make decisions from number of available choices. It uses an integer value or an enumeration type value for making decisions. Switch case is similar to ladder if else.
Syntax:
switch(expression)
{
    case 1: statement/s;
    case 2: statement/s;
    case 3: statement/s;
    ...
    ...
    ...
    case n: statement/s;
    default: statement/s;
}
Here expression is an integer variable, character or an enumeration type whose value is to be matched with case.
Flow chart:
Switch case flow chart
Switch case flow chart


Rules for using switch case:
Lets see a program to understand switch case:

Program:

Write a program to input any week number and print corresponding week name using switch.
#include <stdio.h>

int main()
{
    int week;
    
    printf("Enter week number: ");
    scanf("%d", &week);
    
    switch(week)
    {
        case 1: printf("MONDAY\n");
        case 2: printf("TUESDAY\n");
        case 3: printf("WEDNESDAY\n");
        case 4: printf("THURSDAY\n");
        case 5: printf("FRIDAY\n");
        case 6: printf("SATURDAY\n");
        case 7: printf("SUNDAY\n");
        default: printf("Invalid Input. Please enter week number between 1-7");
    }
    
    return 0;
}

Output:
Enter week number: 4
THURSDAY
FRIDAY
SATURDAY
SUNDAY
Invalid Input. Please enter week number between 1-7
The output of the above program is little weird. When the user input 4 the output should be THURSDAY. But our program is printing all the statements below case 4. In the above program we need something that terminates the control flow from switch when all statements under matched case are executed. And here comes break statement in action.

break: Break statement is used to terminated control flow from inner switch. When a break statement is executed, the control is transferred to next statement after switch.

The above program can be re-written as:
#include <stdio.h>

int main()
{
    int week;

    printf("Enter week number: ");
    scanf("%d", &week);

    switch(week)
    {
        case 1: printf("MONDAY\n");
                break;
        case 2: printf("TUESDAY\n");
                break;
        case 3: printf("WEDNESDAY\n");
                break;
        case 4: printf("THRUSDAY\n");
                break;
        case 5: printf("FRIDAY\n");
                break;
        case 6: printf("SATURDAY\n");
                break;
        case 7: printf("SUNDAY\n");
                break;
        default: printf("Invalid Input. Please enter week number between 1-7");
    }

    return 0;
} 
Output:
Enter week number: 4
THURSDAY

Note: There is no need of break after default case.


You may also like



Labels: , ,