C Switch Statement

The c switch statement is used to execute the code of multiple conditions. In a switch statement, you can not use operators, you have to compare with a direct value like int value, float value, etc.

Switch case statements have multiple cases to execute conditions and a default case that works like as else statement. This statement allows a variable to be compared for equality against a list of values. Each value is known as a case, and the variable being checked for each switch case.

The break statement is optional in the switch statement. If there is no break statement in the switch case, all the switch cases will be executed after matching the case value. It is called fall through the state of C switch statement.


Syntax of Switch Statement

switch(expression/variable_name)
{
case value_1 :
code to be executed;
break; //optional
case value_2 :
code to be executed;
break;//optional
.
.
.
case value_n :
code to be executed;
break;//optional
default :
code to be executed;
}


Example of Switch Statement

//Program to check whether a value of number is equal to 10, 20 and 30
#include<stdio.h>
int main()
{
	int number;
	
	printf("enter the number=");
	scanf("%d",&number);
	
	switch(number)
	{
		case 10:
			printf("number is equal to %d",number);
		break;
		case 20:
			printf("number is equal to %d",number);
		break;
		case 30:
			printf("number is equal to %d",number);
		break;
		default:
			printf("number is not equal to 10, 20 and 20");
	}
	reuturn 0;
}


                                        
            
Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.