C++ Switch Statement:- The Switch statement provide an alternative to else if construct.Use the switch statement to select one of many code blocks to be executed.
syntax is:- switch(expression)
C++ Break statement:- The break statement is used to terminate control from loop statement or exit from switch statement.It can be used with for,while, do-while and switch statement.
syntax is:- break;
syntax of switch and break is:-
switch(expression){
case 1:
// code bolck;
break;
case 2:
// code block;
break;
dedault:
//code block;
}
This is how it works:
- The
switchexpression is evaluated once - The value of the expression is compared with the values of each
case - If there is a match, the associated block of code is executed
- The
breakanddefaultkeywords are optional, and will be described later in this chapter
Example:-
#include<iostream>
using namespace std;
int main(){
int day;
cout<<"Enter a Day:";
cin>>day;
switch(day){
case 1:
cout<<"Sunday";
break;
case 2:
cout<<"Monday";
break;
case 3:
cout<<"Tuesday";
break;
case 4:
cout << "Wednesday";
break;
default:
cout<<"Day does not found!";
}
}
OUTPUT:-
Enter a Day:2
Monday