C switch Statements

C switch statement is used when you have multiple possibilities for the if statement.

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>

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 true, the default case will be executed, and break statement is not required for default statement.


Here are few other related articles for you to read:

Scroll Back to Top