Programing switch() in C++
Q18.Write a C++ program to accept code the display the message as given in the table below.
Code | Message |
1 | This is red |
2 or 3 | Rhis is blue |
4 | This is green |
5 | This is pink |
6 or 7 | This is purple |
otherwise | Wrong code |
First we will write the program using if-else
Program-18
#include <iostream.h> void main(){ int a; cout<<"Enter the code:"; cin>>a; if(a==1){ cout<<"This is red"; } else if(a==2 || a==3){ cout<<"This is blue"; } else if(a==4){ cout<<"This is green"; } else if(a==5){ cout<<"This is pink"; } else if(a==6 || a==7){ cout<<"This is purple"; } else{ cout<<"Wrong code"; } }
#include <iostream.h> void main(){ int a; cout<<"Enter the code:"; cin>>a; switch(a){ case 1: cout<<"This is red"; break; case 2: case 3: cout<<"This is blue"; break; case 4: cout<<"This is green"; break; case 5: cout<<"This is pink"; break; case 6: case 7: cout<<"This is purple"; break; default: cout<<"Wrong code"; } }Points to be remmembered while using switch:
- The variable on which switch operates must be either "int" or "char" type.
- It checks only the equality condition
- Between the word "case" and its value there must be a gap e.g case<gap>1, the colon (:) is part of syntax must be used after every case. Multiple statement can be written one after another under a case as per requirment. Each case must be terminated using break statement. If break statement is not given after any case then cases after it also gets executed so long it does not get a break statement, which is called fall through
- If used with "char" value the case value must be enclosed by single quotes e.g 'a', 'x' etc;
- If the given value does not match with any case value the it executes the default case, which must be the last case.
- In the above program see that case 2 and case 3 when value of "a" is 2 then it executes case 2 which is empty, but see that break is not given so it will fall through and executes the next case also. When the value of "a" is 3 then it will execute case 3 as usual. Therefore case 2 and case 3 together will work as "a==2 || a==3".
Program-19
#include <iostream.h> void main(){ char a; cout<<"Enter the character:"; cin>>a; switch(a){ case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U':cout<<"This is a vowel"; default: cout<<"This is not vowel"; } }Assignment: Write program - 19 using if-else yourself.