How to print every month between two years 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>

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

// ------------------------------------------------------------
// Helper: check if a year is a leap year
// ------------------------------------------------------------
int isLeap(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

// ------------------------------------------------------------
// Helper: Zeller's congruence to compute weekday of a date
// Returns: 0=Saturday, 1=Sunday, ..., 6=Friday
// ------------------------------------------------------------
int weekday(int year, int month, int day) {
    if (month < 3) {
        month += 12;
        year -= 1;
    }
    int K = year % 100;
    int J = year / 100;
    int h = (day + (13*(month + 1))/5 + K + K/4 + J/4 + 5*J) % 7;
    
    return h;
}

// ------------------------------------------------------------
// Function: returns true if a month has 5 full weekends
// ------------------------------------------------------------
int hasFiveFullWeekends(int year, int month) {
    int daysInMonth;

    // Days in each month
    int monthDays[12] = {
        31, 28, 31, 30, 31, 30,
        31, 31, 30, 31, 30, 31
    };

    daysInMonth = monthDays[month - 1];
    if (month == 2 && isLeap(year)) {
        daysInMonth = 29;
    }

    int wd = weekday(year, month, 1); // Zeller: Friday = 6

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

// ------------------------------------------------------------
// Main program
// ------------------------------------------------------------
int main() {
    int startYear = 2026;
    int endYear   = 2030;

    for (int y = startYear; y <= endYear; y++) {
        printf("%d ", y);

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

    return 0;
}


/*
run:

2026 
May 2026 has five full weekends.
2027 
January 2027 has five full weekends.
October 2027 has five full weekends.
2028 
December 2028 has five full weekends.
2029 
2030 
March 2030 has five full weekends.

*/

 



answered May 27 by avibootz

Related questions

...