Switch Statement In C language
“A nail penetrates the wall only when the force of the hammer hits it. Don’t depend on external force, don’t be a nail. Be yourself and develop your own internal force to penetrate through anything that comes your way.”
Hello all.. … . Hope you all are doing well. Let’s force ourselves to penetrate our problems and try to find solutions for the same.
Today we are going to see Switch statement in C language……So let’s start quickly 🙂
C Switch Statement:-
The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple operations for the different possible values of a single variable called switch variable.
Here, We can define various statements in the multiple cases for the different values of a single variable.
Rules for switch statement in C language:-
1)The switch expression must be of an integer or character type.
2) The case value must be an integer or character constant.
3) The case value can be used only inside the switch statement.
4) The break statement in switch case is not must. It is optional. If there is no break statement found in the case, all the cases will be executed present after the matched case. It is known as fall through the state of C switch statement.
5) No two cases can have similar values.
6) If the matched case contains a break statement, then all the cases present after that will be skipped, and the control comes out of the switch.
Break statement:-
The break statement is primarily used as the exit statement, which helps in escaping from the current block or loop.
Note:-If we do not use the break statement, all the statements after the matching case are also executed.
Syntax of switch statement:-
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
……
default:
code to be executed if all cases are not matched;
}
Now we will see one simple example on Switch statement.
Q1) C program to check whether the given number is equal to 1,2 or 3 using switch statement.
#include<stdio.h>
main()
{
int number=0;
printf("enter a number:");
scanf("%d",&number);
switch(number)
{
case 1:
printf("number is equals to 1");
break;
case 2:
printf("number is equal to 2");
break;
case 3:
printf("number is equal to 3");
break;
default:
printf("number is not equal to 1,2 or 3");
}
}
Similarly ,we can write switch statement inside the loops……. We will see that in the upcoming articles soo be connected……
Soo that’s it for today……..I hope you must have got an idea about switch statement.
Thank you so much all for your support….. Will meet in next article.. Till then good bye….. Have a wonderful day ahead:)
You must log in to post a comment.