C++ Code Example: get weekday

The code defines a function getWeekDay that takes an integer num as argument and returns a string that corresponds to the weekday that corresponds to that number.

The function uses a switch statement to check the value of num and return the corresponding string. If num does not correspond to a valid weekday (i.e., if it’s not between 1 and 7), the function returns the string “no valid value”.

The main function simply calls getWeekDay with an argument of 3 and prints the returned string to the console.

#include <iostream>
using namespace std;

string getWeekDay(int num) {
    switch (num) {
        case 1:
            return "Monday";
            break;
        case 2:
            return "Tuesday";
            break;
        case 3:
            return "Wednesday";
            break;
        case 4:
            return "Thursday";
            break;
        case 5:
            return "Friday";
            break;
        case 6:
            return "Saturday";
            break;
        case 7:
            return "Sunday";
            break;
        default:
            return "no valid value";
    }
}

int main() {
    int num = 3;
    cout << "Weekday of number 3 is: " << getWeekDay(num) << endl;
}
Output
Weekday of number 3 is: Wednesday