press 1 if you want idli, 2 for dosa, 3 for chapathi and so on for these type of case we use this.
- IDLI
- DOSA
- CHAPATHI
- PURI
- BIRYANI
- CHICKEN BIRYANI
Syntax:-
switch() { case : ......................... ....statement1......; .......................... break; case ......................... ....statement2......; .......................... break; default: ......................... ....statement1......; .......................... break; }Explanation:-
The statement checks the value in the variable and executes the statements corresponding to that variable.
Default:- The statement in it will execute only when none of the cases got evaluated.Default is not mandatory but for the user to understand that he has given a choice which is out of the context we use this.
break*:- Wen one of the case is executed then corresponding break is executed and comes out of case and goes to the next line after the in case in main().
*-press on the break to get more info on break.
You can give an number of cases
Let us do for the menu given at 1st paragraph.
Program:-
Output:- case1:-When one of the options is selected.
case 2:-When other option is given which is other than 1-5.
Now let us take an example from if else which I have already explained in the other pages about VIBGYOR. Goto the link and see the program "To print color of your interest" and see how we convert that into switch case.
Program:-
#include<stdio.h> main() { char d; printf("Enter a letter V-violet,I-Indigo,B-blue,G-green,Y-yellow,O-orange,R-red\n"); scanf("%c",&d); switch(d) { case 'v': case 'V': printf("Violet\n"); break; case 'i': case 'I': printf("Indigo\n"); break; case 'b': case 'B': printf("Blue\n"); break; case 'g': case 'G': printf("Green\n"); break; case 'y': case 'Y': printf("Yellow\n"); break; case 'o': case 'O': printf("Orange\n"); break; case 'r': case 'R': printf("Red\n"); break; default: printf("Invalid Choice"); break; } }
Copy and paste above program and save it with '.c' extension and execute yourself.
Output:-
case I:- Enter a letter V-violet,I-Indigo,B-blue,G-green,Y-yellow,O-orange,R-red v Violet case II:- Enter a letter V-violet,I-Indigo,B-blue,G-green,Y-yellow,O-orange,R-red V Violet case III:- Enter a letter V-violet,I-Indigo,B-blue,G-green,Y-yellow,O-orange,R-red B Blue Case IV:- Enter a letter V-violet,I-Indigo,B-blue,G-green,Y-yellow,O-orange,R-red X Invalid choice.
In the above program we can't give "OR" condition (||) but it checks both the cases which are written consecutively and It checks both and if any one is correct then it executes corresponding statements.
Try the above program without default and execute to see what will happen.
Observe the output so that you can understand.
No comments:
Post a Comment