Switch Case Statement in C Programming

This is a multiple or multiway branching decision making statement.

When we use nested if-else statement to check more than 1 conditions then the complexity of a program increases in case of a lot of conditions. Thus, the program is difficult to read and maintain. So to overcome this problem, C provides ‘switch case’.

Switch case checks the value of a given expression against a case values, if condition matches the case values then the control is transferred to that point.

Syntax:

switch(expression)
{
	case expr1:
		statements;
		break;
	case expr2:
		statements;
		break;

        ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' 
        ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' 

	case exprn:
		statements;
		break;						
	default:
		statements;
}

In above syntax, switch, case, break are keywords.
expr1, expr2 are known as ‘case labels.’
Statements inside case expression need not to be closed in braces.
Break statement causes an exit from switch statement.
Default case is optional case. When neither any match found, it executes.

Program :

/*  Program to demonstrate switch case statement.
Creation Date : 09 Nov 2010 03:03:57 AM
Author : www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>
#include <conio.h>

int main(void)
{
	int no;
	clrscr();
	printf("\n Enter any number from 1 to 3 : ");
	scanf("%d",&no);
	switch(no)
	{
		case 1:
			printf("\n\n It is 1 !");
			break;
		case 2:
			printf("\n\n It is 2 !");
			break;
		case 3:
			printf("\n\n It is 3 !");
			break;
		default:
			printf("\n\n Invalid number !");
	}
	getch();
	return 0;
}

Output 1 :

Enter any number from 1 to 3 : 3

It is 3 !_

Output 2 :

Enter any number from 1 to 3 : 5

Invalid number !_

* RULES FOR DECLARING SWITCH CASE :

•	The case label should be integer or character constant.
•	Each compound statement of a switch case should contain 
        break statement to exit from case.
•	Case labels must end with (:) colon.

* ADVANTAGES OF SWITCH CASE :

•	Easy to use.
•	Easy to find out errors.
•	Debugging is made easy in switch case.
•	Complexity of a program is minimized.

Leave A Comment

Your email address will not be published. Required fields are marked *