Switch case statement in C language
In this tutorial, we will discuss the concept of the Switch case statement in C language
Switch case in c language
A Switch statement helps a variable for compare against a list of values. Each value called a case. Value of every case statements can be checked for equality value of switch statement
In this tutorial, We can understand the switch case statement in C language. we can have any number of case statements within a switch and each case statement ending a colon with a value able to compare
Every case statements inside the switch statement must be the same data type of the variable and case statement must be unique.
when checking all case statement, if there are false, default statement executed and output is displayed
syntax
switch (x)
{
case statement1:
// code to be executed if n is equal to statement(s) 1;
break;
case statement2:
// code to be executed if n is equal to statement(s) 2;
break;
case statement2:
// code to be executed if n is equal to statement(s) 3;
break; .
.
.
default:
// code to be executed if n doesn’t match any constant
}
Flow diagram
How to work switch statements
- The switch statement is evaluated once
- The value of the switch expression is compared with the value of each case.
- When there is a match of the particular case, the associated block of statements is executed.
- When there is not match any cases, the default statement is executed.
Program 1
#include <stdio.h>
#include <stdlib.h>
int main()
{
int marks=30; //local variable diclaration
switch(marks){
case 90: //if marks is 90
printf(“Excellentn”); //display this statement
break;
case 80: //if marks is 80
printf(“very welln”); //display this statement
break;
case 70: //if marks is 70
printf(“you are a clever studentn”); //display this statement
break;
case 60: //if marks is 60
printf(“you passedn”); //display this statement
break;
case 50: //if marks is 50
printf(“better try againn”); //display this statement
break;
case 40: //if marks is 40
printf(“not enough try againn”); //display this statement
break;
case 30: //if marks is 30
printf(“sorry you are failn”); //display this statement
break;
default:
printf(“not a marksn”); //every cases are false
break; //display default statement
}
printf(“your marks is:%dn”,marks);
return 0;
}
The above code is executed, it produces following reault
at the above program, value of every case compare the value of switch statement
case 60: //if marks is 60
printf(“you passed”); //display this statement
break;
value is 60; this case be equal to switch, so this statement is displayed
When the above code is executed, it produced the following result
you passed
your marks is :60
Suggetsed for you
For Loop in C++ For Loop in C For loop in java
Switch statement in Java Switch statement in C++
Related