Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

How to compute the day of the week for January 1st of any given year in C++

1 Answer

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

/*
    This program computes the day of the week for January 1st of a given year.

    Approach:
    ---------
    1. Fill a std::tm structure with the desired date: January 1st of the input year.
    2. Call std::mktime, which normalizes the structure and computes the calendar fields.
    3. Read tm_wday (0 = Sunday, 1 = Monday, ..., 6 = Saturday).
    4. Convert tm_wday to a human-readable string.

    This uses the standard library's built-in date/time functions,
    avoiding manual calendar arithmetic while remaining portable and efficient.
*/

// Convert tm_wday (0..6) to a weekday name
std::string weekday_to_string(int wday) {
    switch (wday) {
        case 0: return "Sunday";
        case 1: return "Monday";
        case 2: return "Tuesday";
        case 3: return "Wednesday";
        case 4: return "Thursday";
        case 5: return "Friday";
        case 6: return "Saturday";
        default: return "Unknown";
    }
}

// Compute weekday of January 1st for a given year
std::string jan1_weekday(int year) {
    std::tm date{};
    // Years since 1900
    date.tm_year = year - 1900;
    // January (0-based)
    date.tm_mon  = 0;
    // Day of month
    date.tm_mday = 1;
    // Let mktime fill in the rest (tm_wday, etc.)
    std::mktime(&date);

    return weekday_to_string(date.tm_wday);
}

int main() {
    int year = 2026;

    std::string result = jan1_weekday(year);
    std::cout << "January 1st, " << year << " falls on a " << result << ".\n";
}



/*
run:

January 1st, 2026 falls on a Thursday.

*/

 



answered Jul 10 by avibootz

Related questions

...