WAP to print DAY according to user input for day count
Objective
Write a C++ program to print the string name of a Day given its number using switch-case.
Algorithm / Approach
- Read a day number
a. - Pass the variable into a switch block:
switch(a). - Create cases for each day:
case 1: cout << "Monday"; break;. - Include a
default:block to handle invalid numbers.
main.cpp
#include<iostream>
using namespace std;
int main() {
int a;
cout<<"Enter Day Number: ";
cin>>a;
switch(a) {
case 1:
cout<<"Day is Monday\n";
break;
case 2:
cout<<"Day is Tuesday\n";
break;
case 3:
cout<<"Day is Wednesday\n";
break;
case 4:
cout<<"Day is Thursday\n";
break;
case 5:
cout<<"Day is Friday\n";
break;
case 6:
cout<<"Day is Saturday\n";
break;
case 7:
cout<<"Day is Sunday\n";
break;
default:
cout<<"Wrong Choice\n";
}
return 0;
}
Expected Output
Enter Day Number: 4 Day is Thursday
Explanation of the Program
- The
switchstatement is a cleaner, more readable alternative to writing a massive block ofelse ifstatements when you are comparing a single integer or character against exact constant values. - The
breakkeyword is mandatory at the end of every case. If you forget it, the program will suffer from "fall-through" and execute all the cases below the matching one as well.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)