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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,888 questions

51,815 answers

573 users

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 66 views
1 answer 68 views
2 answers 67 views
2 answers 62 views
1 answer 68 views
1 answer 64 views
...