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 <stdio.h>
#include <stdbool.h>

// ------------------------------------------------------------
// Month names as a single reusable constant
// ------------------------------------------------------------
const char *monthNames[12] = {
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
};

// ------------------------------------------------------------
// Zeller's congruence (returns 0=Saturday, 1=Sunday, ..., 6=Friday)
// ------------------------------------------------------------
int weekday_of_date(int year, int month, int day) {
    if (month < 3) {
        month += 12;
        year -= 1;
    }

    int K = year % 100;
    int J = year / 100;
    // Zeller’s congruence - formula for computing the day of the week 
    // for any Gregorian date.
    int h = (day + (13 * (month + 1)) / 5 + K + K/4 + J/4 + 5*J) % 7;
    
    return h;  // 0=Saturday, 6=Friday
}

// ------------------------------------------------------------
// Function: returns true if a month has 5 full weekends
// ------------------------------------------------------------
bool hasFiveFullWeekends(int year, unsigned m) {
    int daysInMonth[12] = {
        31,28,31,30,31,30,31,31,30,31,30,31
    };

    // Leap year adjustment
    bool leap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
    if (leap)
        daysInMonth[1] = 29;

    int days = daysInMonth[m - 1];

    // First day of the month
    int wd = weekday_of_date(year, m, 1);

    // Zeller: Friday = 6
    return (days == 31 && wd == 6);
}

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

    for (int m = 1; m <= 12; m++) {
        if (hasFiveFullWeekends(y_value, (unsigned)m)) {
            printf("%s %d has five full weekends.\n",
                   monthNames[m - 1], y_value);
        }
    }

    return 0;
}


/*
run:

May 2026 has five full weekends.

*/

 



answered May 26 by avibootz
edited May 26 by avibootz

Related questions

...