How to calculate the number of weekdays in the current year with C

1 Answer

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

int getCurrentYear() {
    time_t t = time(NULL);
    struct tm *lt = localtime(&t);
    
    return lt->tm_year + 1900;
}

int isWeekday(int year, int month, int day) {
    struct tm time_in = { 0, 0, 0, day, month - 1, year - 1900 };
    mktime(&time_in);
    int wday = time_in.tm_wday;
    
    return (wday != 0 && wday != 6); // 0 = Sunday, 6 = Saturday
}

int countWeekdays(int year) {
    int weekdays = 0;
    
    for (int month = 1; month <= 12; month++) {
        for (int day = 1; day <= 31; day++) {
            struct tm time_in = { 0, 0, 0, day, month - 1, year - 1900 };
            if (mktime(&time_in) != -1 && time_in.tm_mon == month - 1) {
                if (isWeekday(year, month, day)) {
                    ++weekdays;
                }
            }
        }
    }
    
    return weekdays;
}

int main() {
    int currentYear = getCurrentYear();
    int weekdays = countWeekdays(currentYear);
    
    printf("Number of weekdays in %d is: %d\n", currentYear, weekdays);
    
    return 0;
}

  
  
/*
run:
  
Number of weekdays in 2025 is: 261
  
*/

 



answered Feb 18, 2025 by avibootz

Related questions

1 answer 81 views
1 answer 88 views
2 answers 86 views
1 answer 105 views
2 answers 77 views
1 answer 87 views
1 answer 80 views
...