Calendar Functions

franka at mmintl.UUCP franka at mmintl.UUCP
Tue Sep 16 04:38:56 AEST 1986


In article <1229 at loral.UUCP> dml at loral.UUCP (Dave Lewis) writes:
>daysinmonth (month, year)
>int month, year;
>{
>  if (month == 2)          /* Is it February?             */
>     if (leapyear (year))  /* If so, is it a leap year?   */
>	return (29);       /* 29 days in Feb in leap year */
>     else
>	return (28);       /* 28 days if not              */
>  else{
>     if (month > 7)        /* Is it August -> December?   */
>	month++;           /* Invert even/odd state if so */
>     if (month & 1)        /* Odd months have 31 days     */
>	return (31);
>     else
>	return (30);       /* Even months have 30 days    */
>  }
>}

This is ok, but it is easier to use a table:

daysinmonth(month, year)
int month, year)
{
   int monthlengths[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

   if (month == 2 && leapyear(year)) {
      return (29);
   } else {
      return monthlengths[month - 1];
   }
}

(Comments are left as an exercise for the reader.)

Frank Adams                           ihnp4!philabs!pwa-b!mmintl!franka
Multimate International    52 Oakland Ave North    E. Hartford, CT 06108



More information about the Comp.lang.c mailing list