Search code examples
cformulacomputer-science

First Day of the year Formula resulting in inconsistent results


The objective is to find the first day of the year, and subsequently calculate calendars based off of that, and leap years. The issue I'm running into is; while the class was given a formula (unable to use arrays or functions), I'm able to get a proper result for most given years, except when it comes to calculating saturdays (a 0 for a remainder after modulus.)

Is my formula way off?

I will link the page that breaks down the formula and of course provide mine.

**Here is the page with the formula: **

Math Forum - Formula for the First Day of a Year

Here is my formula with my code:

 //Calculating Dates:
//N = d + 2m + [3(m+1)/5] + y + [y/4] - [y/100] + [y/400] + 2
//N = 1 + 2(13) + [3(13+1)/5] + year_int + [year_int/4] - [year_int/100] + 
//[year_int/400] + 2
// I'm using a hard-coded "13" to represent January in the place of m
 day_one =
        1 + 2*(13) + 3*(13 + 1)/5 + year_int + (year_int / 4) - (year_int / 100) + (year_int / 400) +
        2;
day_one = day_one % 7;


if (day_one < 0 || day_one >= 7) {
printf("Invalid Day\n");
} else {
switch (day_one) {


    case 1:
        weekday = "Sunday";
        printf("%s", weekday);
        break;
    case 2:
        weekday = "Monday";
        printf("%s", weekday);
        break;
    case 3:
        weekday = "Tuesday";
        printf("%s", weekday);
        break;
    case 4:
        weekday = "Wednesday";
        printf("%s", weekday);
        break;
    case 5:
        weekday = "Thursday";
        printf("%s", weekday);
        break;
    case 6:
        weekday = "Friday";
        printf("%s", weekday);
        break;
    case 0:
        weekday = "Saturday";
        printf("%s", weekday);
        break;
    default: printf("Error");
    break;
}
}

I truly appreciate any assistance, I'm only looking for guidance.

Thank you!


Solution

  • I hope that this is more clear. Please see the comment with !!! inside the function

    /* 
    ZELLER'S Algorithm
    https://en.wikipedia.org/wiki/Zeller's_congruence
    Gregorian calendar
    */
     #include <stdio.h>
    
     int day_of_week(int d,int m,int y);
     int main(void)
     {
      int day,month,year;
      printf ("Day, Month, Year\n");
      scanf ("%d %d %d",&day,&month,&year); 
      printf("%d",day_of_week(day,month,year)); 
      return 0;
     }
    
     int day_of_week(int d, int m, int y)
     //This function returns the ISO number of the day for a given day,month,year
     {
      int day;  
      if (d<1 || d>31 || m<1 || m>12 || y<1583 ) return 0; // In that case we have major error!
      if ((m==1) || (m==2)) 
        {m=m+12;--y;} // You have to do this correction !!!!
      day=d+(m+1)*26/10+y+y/4+6*(y/100)+y/400;
      day=day % 7; // 0=Saturday 1=Sunday ...
      day=((day+5) % 7)+1; // Convertion to ISO date: 1=Monday, 2=Tuesday ..
      return (day);
     }