How to use a Switch-Case in C++ programme| switch- default- use
A switch statement allows a variable to be checked for equality for a list of values. Each value is called a case. If that value entered by the user matches the case value , the statements followed by that case are executed.
This is an alternate to if-else control.
(There are some differences between if-else and switch case)
Syntax:
switch(expression)
{
case a:
// statement(s)
break;
case b:
//statement(s)
break;
case c:
// statement(s)
default:
// statement(s)
}
As control reaches a break keyword, it exits the switch block.
The default keyword executes when there is no match found.
The break keyword has very significant role to play.
switch(expression)
{
case a:
// statement(s)
break;
case b:
//statement(s)
break;
case c:
// statement(s)
default:
// statement(s)
}
As control reaches a break keyword, it exits the switch block.
The default keyword executes when there is no match found.
The break keyword has very significant role to play.
//use header files syntax according to the compiler
#include<iostream.h>
#include<conio.h>
void main()
{
int day;
cout<<"enter a day of the week:";
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;
case 7:
cout << "sunday";
break;
default:
cout<<"invalid day number:";
}
getch();
}
//if input value is 1 then output would be "monday".
//if input value is 9 then output would be "invalid day number".