Switch statement in C ?
Switch statement is a control statement that allows us to choose only one choice among the many given choices. It is a control statement used to make a selection between many alternatives.
The switch statement is used in the following conditions:-
1.) When a decision has to be made between many alternatives.
2.) When the selection condition reduces to fixed integer value.
Syntax:-
switch(choice)
{
case value 1:
Block -1;
break;
case value 2:
Block –n;
break ;
default:
Block -d
}
Rules for declaring switch statement:-
Statements | Explaination |
---|---|
1.) The expression that follows the keyword switch must be evaluated to an integer . | switch(choice) // valid if choice is an integer variable. switch(i+2) // valid if I is an integer variable. switch(i+2.5) // invalid 2.5 is floating value |
2.) The expression that follows the keyword case should not contain any variables. | case 90+4 // valid case i+2 // invalid since variable I is present . |
3.) Two or more case labels with same value not allowed. | case 1: printf(“ok”); case 1: // invalid case 1 is already defined. printf(“not ok”); |
4.) Two or more case labels can be associated with same statements. | case 1: case 2: case 3: printf(“ok”); // valid |
5.) Let int i ; char c ; float f; double d; |
switch(i) //valid switch(i+10) // valid switch(i+5.5) //invalid switch(c+10) //valid switch(c+d) // invalid d is double floating point not allowed |
6.) case'choice' | // invalid only one character is allowed. |
Q.) W.A.P to print ONE if we press 1, TWO if we press 2 and THREE if we press 3.
#include<stdio.h> #include<conio.h> void main() { int ch; printf(“press any key 1 to 3 ”); scanf(“%d”,&ch); switch(ch) { case 1: printf(“ONE”); break; case 2: printf(“TWO”); break; case 3: printf(“THREE”); break; default: printf(“press only 1 to 3”); }
Output
press any key 1 to 3: 2
TWO
TWO
Copyright © 2022 Shineskill Software Pvt. Ltd., All rights reserved.