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

1 Answer

0 votes
#include <chrono>
#include <iostream>
  
using namespace std::chrono;
  
// Return the last Friday of a specific month
year_month_day last_friday_of_month(int y, unsigned m) {
    year_month ym{year{y}, month{m}};
  
    // First day of next month
    year_month_day first_next = (ym + months{1}) / day{1};
  
    // Last day of this month
    sys_days last_day = sys_days{first_next} - days{1};
  
    // Walk backward to Friday
    while (weekday{last_day} != Friday) {
        last_day -= days{1};
    }
  
    return year_month_day{last_day};
}
  
// Print all last Fridays of each month in a given year
void list_of_last_fridays_of_each_month_in(int year) {
    for (unsigned m = 1; m <= 12; m++) {
        year_month_day d = last_friday_of_month(year, m);
        std::cout << (int)d.year() << "-"
             << (unsigned)d.month() << "-"
             << (unsigned)d.day() << "\n";
    }
}
  
int main() {
    list_of_last_fridays_of_each_month_in(2026);
}
  
  
  
/*
run:
  
2026-1-30
2026-2-27
2026-3-27
2026-4-24
2026-5-29
2026-6-26
2026-7-31
2026-8-28
2026-9-25
2026-10-30
2026-11-27
2026-12-25
  
*/

 



answered May 23 by avibootz
edited May 23 by avibootz

Related questions

...