Online visitors

People learning around the world

Online

—

Visitors exploring W3Schools

Online visitors by country Circles show approximate country locations. The country list provides the visitor counts.

Circles represent countries, not exact visitor locations.

Country

Online

Loading country activity…

    C switch Statements

    In the C program, the switch statement is used when you have multiple possibilities for the if statement. The switch case allows you to choose from several options. For example, when we compare it with a regular electric switchboard, you will have many switches in the switchboard, but you will select only the required buttons; similarly, the switch case allows you to set the necessary statements for the user.

    The basic format of the switch statement is:

    Syntax:

    switch(variable)
    {
        case 1:
        //execute your code
        break;
    
        case n:
        //execute your code
        break;
    
        default:
        //execute your code
        break;
    }

    After the end of each block, it is necessary to insert a break statement because if the programmers do not use the break statement, all consecutive blocks of codes will get executed from every case onwards after matching the case block.

    Example of a C Program to Demonstrate Switch Statement

    Example:

    #include<stdio.h>
    
    void main()
    {
        int a;
        printf("Please enter a no between 1 and 5: ");
        scanf("%d",&a);
        
        switch(a)
        {
            case 1:
            printf("You chose One");
            break;
    
            case 2:
            printf("You chose Two");
            break;
    
            case 3:
            printf("You chose Three");
            break;
    
            case 4:
            printf("You chose Four");
            break;
    
            case 5:
            printf("You chose Five.");
            break;
    
            default :
            printf("Invalid Choice. Enter a no between 1 and 5");
            break;
        }
    } 

    Program Output:

    c-switch

    When none of the cases is evaluated to be true, the default case will be executed, and a break statement is not required for the default statement.

    switch Statements in C - Video Tutorial

    Please watch this video tutorial to understand "C switch Statements" in more depth.



    Found This Page Useful? Share It!
    Get the Latest Tutorials and Updates
    Join us on Telegram

    Notifications

    Updates are enabled for this browser.

    Receive new tutorials, articles and learning resources. You can turn updates off anytime.