| 1. |
Explain switch-case statement with a suitable program example. |
|
Answer» Switch statement compares the value of an expression against a list of integers or character constants. The list of constants is listed using the “case” statement along with a “break” statement to end the execution. #include<iostream.h> int main(void) { int day; cout<<"Enter the day of the week between 1-7::"; cin>>day; switch(day) { case 1: cout<<"Monday"; break; case 2: cout<<"Tuesday"; break; case 3: cout<<"Wednesday"; break; case 4: cout <<"Thursday"; break; case 5: cout <<"Friday"; break; case 6: cout <<"Saturday"; break; default: cout<<"Sunday"; break; } } Result: Enter the day of the week between 1-7::7 Sunday In the above Control Structure example, the “switch” statement is used to find the day of the week from the integer input got from the user. The value present in the day is compared for equality with constants written in the word case. Since no equality is achieved in the above example (from 1 to 6) as the entered value is 7, default value is selected and gives “Sunday” as the result. |
|