How to calculate the future occurrences of Friday the 13th in C++

1 Answer

0 votes
#include <iostream>
#include <ctime>

void findFridayThe13ths(int startYear, int endYear) {
    for (int year = startYear; year <= endYear; ++year) {
        for (int month = 1; month <= 12; month++) {
            // Create a tm structure for the 13th day of the current month and year
            std::tm timeStruct = {};
            timeStruct.tm_year = year - 1900; // tm_year is years since 1900
            timeStruct.tm_mon = month - 1;   // tm_mon is 0-based (0 = January)
            timeStruct.tm_mday = 13;         // 13th day of the month

            // Normalize the tm structure to get the correct day of the week
            std::mktime(&timeStruct);

            // Check if the 13th is a Friday (tm_wday == 5)
            if (timeStruct.tm_wday == 5) {
                std::cout << "Friday the 13th: " << year << "-" 
                          << (month < 10 ? "0" : "") << month << "-13" << std::endl;
            }
        }
    }
}

int main() {
    int startYear = 2025; // Starting year
    int endYear = 2031;   // Ending year

    findFridayThe13ths(startYear, endYear);
}



/*
run:

Friday the 13th: 2025-06-13
Friday the 13th: 2026-02-13
Friday the 13th: 2026-03-13
Friday the 13th: 2026-11-13
Friday the 13th: 2027-08-13
Friday the 13th: 2028-10-13
Friday the 13th: 2029-04-13
Friday the 13th: 2029-07-13
Friday the 13th: 2030-09-13
Friday the 13th: 2030-12-13
Friday the 13th: 2031-06-13

*/

 



answered May 31, 2025 by avibootz
...