How to print every month in a specified year that contains five full weekends (Fri, Sat, Sun) in C++

1 Answer

0 votes
// A month has five full weekends when it has 31 days, and the 1st day of the month is a Friday.

#include <iostream>
#include <chrono>
#include <string>
#include <array>

using namespace std::chrono;

// ------------------------------------------------------------
// Month names as a single reusable constant
// ------------------------------------------------------------
namespace CalendarData {
    constexpr std::array<std::string_view, 12> monthNames = {
        "January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"
    };
}

// ------------------------------------------------------------
// Function: returns true if a month has 5 full weekends
// ------------------------------------------------------------
bool hasFiveFullWeekends(year y, unsigned m) {
    year_month_day firstDay = y / month{m} / day{1};

    sys_days firstSysDay{firstDay};
    weekday wd{firstSysDay};

    year_month ym = y / month{m};
    year_month_day lastDay = ym / last;
    unsigned daysInMonth = static_cast<unsigned>(lastDay.day());

    return (daysInMonth == 31 && wd == Friday);
}

// ------------------------------------------------------------
// Main program
// ------------------------------------------------------------
int main() {
    const int y_value = 2026;
    const year y{y_value};

    using CalendarData::monthNames;

    for (int m = 1; m <= 12; m++) {
        if (hasFiveFullWeekends(y, static_cast<unsigned>(m))) {
            std::cout << monthNames[m - 1] << " " << y_value
                 << " has five full weekends.\n";
        }
    }
}



/*
run:

May 2026 has five full weekends.

*/

 



answered May 26 by avibootz
edited May 26 by avibootz

Related questions

...