Day of week program
This program has the basics for working with days of the week added to it. Use enums to improve the readability and scoping of this code.
#include <iostream>
#include <vector>
// Magic numbers for weekdays
const int MONDAY = 1;
const int TUESDAY = 2;
const int WEDNESDAY = 3;
const int THURSDAY = 4;
const int FRIDAY = 5;
const int SATURDAY = 6;
const int SUNDAY = 7;
std::string getDayName(int day) {
switch (day) {
case MONDAY: return "Monday";
case TUESDAY: return "Tuesday";
case WEDNESDAY: return "Wednesday";
case THURSDAY: return "Thursday";
case FRIDAY: return "Friday";
case SATURDAY: return "Saturday";
case SUNDAY: return "Sunday";
default: return "Invalid day";
}
}
int main() {
std::vector<int> days = {1, 2, 3, 4, 5, 6, 7};
for (int day : days) {
std::cout << "Day " << day << " is " << getDayName(day) << std::endl;
}
return 0;
}
Answer
The variables MONDAY - SUNDAY has been moved into the Weekday enum
#include <iostream>
#include <vector>
// Enum class for weekdays
enum Weekday {
MONDAY = 1,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
};
std::string getDayName(Weekday day) {
switch (day) {
case Weekday::MONDAY: return "Monday";
case Weekday::TUESDAY: return "Tuesday";
case Weekday::WEDNESDAY: return "Wednesday";
case Weekday::THURSDAY: return "Thursday";
case Weekday::FRIDAY: return "Friday";
case Weekday::SATURDAY: return "Saturday";
case Weekday::SUNDAY: return "Sunday";
default: return "Invalid day";
}
}
int main() {
std::vector<Weekday> days = {Weekday::MONDAY, Weekday::TUESDAY, Weekday::WEDNESDAY, Weekday::THURSDAY, Weekday::FRIDAY, Weekday::SATURDAY, Weekday::SUNDAY};
for (Weekday day : days) {
std::cout << "Day " << day << " is " << getDayName(day) << std::endl;
}
return 0;
}