Switch Case in C Programming

  • Switch case statement acts as a substitute for a long if-else-if ladder that is used to test a list of cases.
  • A switch statement contains one or more case labels which are tested against the switch expression.
  • When the expression match to a case then the associated statements with that case would be executed.

Syntax


Switch (expression)
{
case value1:
//Statements
break;
case value 2:
//Statements
break;
case value n:
//Statements
break;

Default:
//Statements
}

For Example,

Write a C Program to find the weekdays name by entering weekday number

#include<stdio.h>
#include<conio.h>
void main()
{
int day;
    printf("Enter Weekday number between 1 to 7 /n : ");
    scanf("%d",&day);

    switch(day) 
	{
        case 1:
            printf("First days of week is Sunday");
            break;
        case 2:
             printf("Second days of week is Monday");
            break;
        case 3:
             printf("Third days of week is Tuesday");
            break;
        case 4:
            printf("Fourth days of week is Wednesday");
            break;
        case 5:
            printf("Fifth days of week is Thursday");
            break;
        case 6:
        	printf("Sixth days of week is Friday");
            break;
        case 7:
            printf("Seventh days of week is Saturday");
            break;
        default:
            printf("Error! invalid weekday selected");
    }
getch();
}
Scroll to Top