-5

I have the C99 as follow:

int dayOfWeek(int day, int month, int year, int firstJan);

The first parameter, day, provides the day of interest − range from 1 to 31 (inclusive). The second parameter, month, provides the month of interest − range from 1 to 12 (inclusive). The third parameter, year, provides the year of interest − any integer value of 1970 or greater. The fourth parameter, firstJan, indicates the day of the week on which the first of January falls in the provided year.

The function will return the day of the week on which the indicated date falls. For example, the call:

dayOfWeek(13, 11, 2017, 0);

will return the integer 1 (representing Monday).

How can I approach the solution? Its permitted values are 0 (representing Sunday), 1 (representing Monday), and so on, up to 6 (representing Saturday). Code has been edit:

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 
  4 int dayOfweek(int day, int month, int year, int firstJan)
  5 {
  6         int mth[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
  7         int mth_leap[] = {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335};
  8 
  9         if(year <1970 || month < 1 || month > 12 || day < 1 || day > 31 || firstJan < 0 || firstJan > 6 ){
 10         printf("invalid input");
 11         //return -1;
 12         }
 13 
 14         if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)){
 15                 day = mth_leap[month - 1] + day ;
 16         }else{
 17                 day = mth[month - 1] + day;
 18         }
 19 
 20         int dow = (day - firstJan + 7)%7;
 21         printf("Day of week is %i.\n", dow);
 22         //return 1;
 23 
 24 }
Jim Ye
  • 77
  • 8

1 Answers1

2

Day of the week is found simply with mktime().

The mktime function

On successful completion, the values of the tm_wday and tm_yday components of the structure are set appropriately, and the other components are set to represent the specified calendar time,

#include <time.h>

int dayOfWeek(int day, int month, int year, int /*firstJan*/) {
   // struct tm members domain are: years from 1900, and months since January
   // Important to set tm_isdst = -1 to let the function determine dst setting.
   struct tm ymd = { .tm_year - 1900, .tm_mon = month - 1, .tm_mday = day, .tm_isdst = -1);

   time_t t = mktime(&ymd);  // this will fill in .tm_wday
   if (t == -1) return -1;  // Failed to find a valid calender time (and day-of-the-week)
   return ymd.tm_wday;
}

How can I approach the solution?

Yet OP has a function that provides the day-of-the-week for Jan 1st.

Some pseudo code for that approach:

int dayOfWeek(int day, int month, int year, int firstJan) {
  days_since_jan1 = table[month] + day;
  if (month > Feb and isleap(year)) days_since_jan1++;
  dow = (days_since_jan1 - firstJan + 7)%7
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256