In: Computer Science
Question: Can you please convert this program into switch case program using c++.
Output should be same
int main()
{
bool weekend = false;
unsigned char day = 0;
bool isDay = true;
cout << " Enter a char for a day of week:";
cin >> day ;
if (day == 'M' || day == 'm')
cout << " This is Monday" << endl ;
else if (day == 'T' || day == 't')
cout << " This is Tuesday" << endl ;
else if (day == 'W' || day == 'w')
cout << " This is Wednesday" << endl ;
else if (day == 'R' || day == 'r')
cout << " This is Thursday" << endl ;
else if (day == 'F' || day == 'f')
cout << " This is Friday" << endl ;
else if (day == 'S' || day == 's')
{
cout << " This is Saturday" << endl ;
weekend = true ;
}
else if (day == 'U' || day == 'u')
{
cout << " This is Sunday " << endl ;
weekend = true ;
}
else
{
cout << day << " is not recognized..." << endl ;
isDay = false;
Required Code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
bool weekend = false;
unsigned char day = 0;
bool isDay = true;
cout << " Enter a char for a day of week:";
cin >> day ;
switch(day) //pass day as parameter of switch
{
case 'M': case 'm': //as we have to use two character
so we can use like that one case for 'M' and one for 'm'
cout << " This is Monday" << endl ;
break; //we need to use break statement after each
statement otherwise all cases it will execute
case 'T': case 't': //as we have to use two character so we can use like that one case for 'M' and one for 'm'
cout << " This is Tuesday" << endl ;
case 'W': case 'w': //as we have to use two character so we can use like that one case for 'M' and one for 'm'
cout << " This is Wednesday" << endl ;
break; //we need to use break statement
after each statement otherwise all cases it will execute
case 'R': case 'r': //as we have to use two character so we can use like that one case for 'M' and one for 'm'
cout << " This is Thursday" << endl ;
break; //we need to use break statement after each
statement otherwise all cases it will execute
case 'F':case 'f': //as we have to use two character so we can use like that one case for 'M' and one for 'm'
cout << " This is Friday" << endl ;
break; //we need to use break statement
after each statement otherwise all cases it will execute
case 'S':case 's': //as we have to use two character so we can use like that one case for 'M' and one for 'm'
cout << " This is Saturday" << endl ;
weekend = true ;
break; //we need to use break statement
after each statement otherwise all cases it will execute
case 'U':case 'u': //as we have
to use two character so we can use like that one case for 'M' and
one for 'm'
cout << " This is Sunday " << endl ;
weekend = true ;
break; //we need to use break statement after each
statement otherwise all cases it will execute
default:
cout << day << " is not recognized..." << endl ;
isDay = false;
}
}