C++ switch Control Statement
The switch control statement allows checking the variable for equality against a list of values. The switch statement checks an integer, char or enumerated type in its condition expression. It does not take any floating variable in its condition expression.
Syntax
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
switch(expression) { case constant-expression : statement(s); break; //optional case constant-expression : statement(s); break; //optional …… default : //Optional statement(s); } |
C++ switch Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#include <iostream> using namespace std; int main () { char grade; cout<<"enter any grade A,B,C,D" << endl; cin>> grade; switch(grade) { case 'A' : cout << "your grade is A" << endl; break; case 'B' : cout << "your grade is B" << endl; break; case 'C' : cout << "your grade is C" << endl; break; case 'D' : cout << "your grade is D" << endl; break; default : cout << "Invalid grade" << endl; } cout << "Your grade is " << grade << endl; return 0; } |
Output
1 2 3 4 5 |
enter any grade A,B,C,D C your grade is C |