What is a Switch Case In C With An Example:

Share Your Love

A switch statement allows a variable to compare with case labels for equality if match that statement is going to be executed. Each case labels are compared with the switch statement or variable, if matched then that case-labels implemented otherwise default statement is going to be print.

Example of Switch Case:

#include<stdio.h>//header file for standard input and output
int main()//main function defined as integer
{//main func braces opened
	int mn;//variable mn of integer type to store month number
	printf("Enter the month number");//print message
	scanf("%d".&mn);//user input for month number
	switch(mn)//switch case to test cases for month name
	{//switch case braces opened
		case 1://start of test cases as 1,2,3…12 as there are 12 months
			printf("January");//print message
			break;//break statement, if this particular case satisfies then it comes out of the switch block
		case 2:
			printf("Feburary");
			break;
		case 3:
			printf("March");
			break;
		case 4:
			printf("April");
			break;
		case 5:
			printf("May");
			break;
		case 6:
			printf("June");
			break;
		case 7:
			printf("July");
			break;
		case 8:
			printf("August");
			break;
		case 9:
			printf("September");
			break;
		case 10:
			printf("October");
			break;
		case 11:
			printf("November");
			break;
		case 12:
			printf("December");
			break;
		default://it gets encountered where there is no match from the above test cases for instance in this program if the month number is greater than 12 this gets encountered as we do not have any month after 12
			printf("Invalid Month number");
		}//switch case braces closed
	return 0;
}//main function braces closed

Please write comments or WhatsApp if you find anything incorrect, or you want to share more information about the topic discussed above.

Share Your Love
Avatar photo
Soham Malakar

Hello my name is Soham Malakar am currently pursuing BCA

Coding is one of my favorite hobbies.
I love to code and an enthusiast to learn different types of programming languages.
I love to get intoxicated in the world of technology and video games.
A quick learner possessing better results.

Articles: 40

Newsletter Updates

Enter your email address below to subscribe to our newsletter