‘switch’ statement is used to execute a block of code from many alternatives or cases. The expression of the switch statement is compared with the case and if true the code is executed. If it is false the next case is compared. If a case is true, break statement breaks the execution of any further cases. If no cases are true ‘default’ is executed.
The expression of the switch statement should be of type integral or should result into an integral type. The following program shows selection of a fruit name using switch-case statement.
#include<iostream>
using namespace std;
int main () {
char fruits;
cout<<"Enter the first character of a fruit: 'Banana','Orange','Apple, 'Grapes': ";
cin>> fruits;
switch (fruits)
{
case 'B':
cout<<"The fruit is Banana";
break;
case 'O':
cout<<"The fruit is Orange";
break;
case 'A':
cout<<"The fruit is Apple";
break;
case 'G':
cout<<"The fruit is Grapes";
break;
default:
cout<<"No fruit is selected";
}
}
Output1:
Enter the first character of a fruit: 'Banana','Orange','Apple, 'Grapes': O
The fruit is Orange
Output2:
Enter the first character of a fruit: 'Banana','Orange','Apple, 'Grapes': G
The fruit is Grapes
Output:3
Enter the first character of a fruit: 'Banana','Orange','Apple, 'Grapes': Z
No fruit is selected