How to find the dates of the last Sunday of each month of a given year in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

/* Simple date structure */
typedef struct {
    int year;
    int month;
    int day;
} Date;
 
/* Check if a year is leap year */
int is_leap(int y) {
    if (y % 400 == 0) return 1;
    if (y % 100 == 0) return 0;
    return (y % 4 == 0);
}
 
/* Days in each month */
int days_in_month(int y, int m) {
    static const int mdays[12] =
        {31,28,31,30,31,30,31,31,30,31,30,31};
 
    if (m == 2 && is_leap(y))
        return 29;
 
    return mdays[m - 1];
}
 
/*
    Pure arithmetic weekday:
    Returns:
        0 = Monday
        1 = Tuesday
        2 = Wednesday
        3 = Thursday
        4 = Friday
        5 = Saturday
        6 = Sunday
*/
int weekday_monday0(int y, int m, int d) {
    long days = 0;
 
    for (int yr = 1; yr < y; yr++)
        days += is_leap(yr) ? 366 : 365;
 
    for (int mo = 1; mo < m; mo++)
        days += days_in_month(y, mo);
 
    days += (d - 1);
 
    return (int)(days % 7);
}
 
/*
    // Return the last Sunday of a specific month
*/
Date last_sunday_of_month(int y, unsigned m) {
    Date result;
 
    int last = days_in_month(y, m);
 
    /* Walk backward to Sunday */
    for (int d = last; d >= 1; d--) {
        int w = weekday_monday0(y, m, d);
 
        /* Sunday = 6 */
        if (w == 6) {
            result.year = y;
            result.month = m;
            result.day = d;
            return result;
        }
    }
 
    result.year = y;
    result.month = m;
    result.day = 1;
    
    return result;
}
 
/*
    // Print all last Sundays of each month in a given year
*/
void list_of_last_sundays_of_each_month_in(int year) {
    for (unsigned m = 1; m <= 12; ++m) {
        Date d = last_sunday_of_month(year, m);
        printf("%02d/%02d/%04d\n", d.month, d.day, d.year);
    }
}
 
int main(int argc, char *argv[]) {
    int year = 2026;

    if (argc > 1) {
        year = (int)strtol(argv[1], NULL, 10);
    }
        
    list_of_last_sundays_of_each_month_in(year);
     
    return 0;
}
 
 
 
/*
run:
 
01/25/2026
02/22/2026
03/29/2026
04/26/2026
05/31/2026
06/28/2026
07/26/2026
08/30/2026
09/27/2026
10/25/2026
11/29/2026
12/27/2026
 
*/

 



answered 13 hours ago by avibootz
edited 10 hours ago by avibootz

Related questions

...