The switch statement is a multi-way decision that tests whether an expression matches one of a number of constant integer (or character) values, and branches accordingly. If a case matches
switch statement
The general form of the switch statement is:
switch (variable_expression) {
case constant 1:
statement sequence 1;
break;
case constant 2:
statement sequence 2;
break;
case constant 3:
statement sequence 3;
break;
default:
statement sequence 4;
}
In a switch statement, a variable is successively tested against a list of integer or character constants. If a match is found, a statement of block of statements is executed. The default part of the switch is executed if no matches are found.
According to Herbert Schildt (1992), there are three important things to know about switch statements:
The switch differs from if statements in such a way that switch can only test for equality whereas if can evaluate a relational or logical expression.
No two case constant in the same switch can have identical values. Of course, a switch statement enclosed by an outer switch may have case constants that are the same.
If character constants are used in the switch, they are automatically converted to their integer values.
NOTE: The break statement is used to exit/terminate the statement sequence associated with each case constant. It is a Turbo C keyword which means that at that point of execution, you should jump to the end of the switch statement terminated by the closing curly brace ( {} ) symbol.
Example 1:
/* Write a program to display the high school level of a student, based on its year-entry number. For example, 1 means the student is a freshmen, 2 for sophomore, and so on. */
#include <iostream>
using namespace std;
int J;
int main() {
cout << "\n ENTER THE YEAR LEVEL\n";
cin >> J;
switch(J) {
case 1:
cout << "\n "FRESHMAN";
break;
case 2:
cout << "\n SOPHOMORE";
break;
case 3:
cout << "\n JUNIOR";
break;
case 4:
cout << "\n SENIOR";
break;
default:
cout << "\n OUT OF SCHOOL";
}
//end of switch
return 0;
}
SAMPLE OUTPUT:
ENTER YEAR LEVEL:
1
FRESHMAN
Here is your video explaining more about switch statement: