CS13002 PDS Lab, Spring 2003, Section 1/A

Supplementary Lab Test : Solution

#include <stdio.h>

#define MAX_TRY 50

void printDate ( int n )
/* Formatted printing of a day encoded by an integer between 0 and 364 */
{
   int nDays[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
   int m;

   /* Determine the month */
   m = 0;
   while (n >= nDays[m]) n -= nDays[m++];

   /* Print the name of the month */
   switch (m) {
      case 0 : printf("January"); break;
      case 1 : printf("February"); break;
      case 2 : printf("March"); break;
      case 3 : printf("April"); break;
      case 4 : printf("May"); break;
      case 5 : printf("June"); break;
      case 6 : printf("July"); break;
      case 7 : printf("August"); break;
      case 8 : printf("September"); break;
      case 9 : printf("October"); break;
      case 10 : printf("November"); break;
      default : printf("December"); break;
   }

   /* Print the date */
   printf(" %d\n", n+1);
}

void checkMatch ( int i , int n , int bday[] )
{
   int j;

   for (j=0; j<i; j++) if (bday[j] == n) {
      printf("Match found among %d birthdays.\n",i+1);
      printf("Birthdays no. %d and %d are the same...\n",j+1,i+1);
      exit(0);
   }

   /* No match found. Store the day for future comparisons. */
   bday[i] = n;
}

int main ()
{
   int i, n;
   int bday[MAX_TRY];

   /* Seed the random number generator with current time in order to get
      different outputs on different runs. */
   srand((unsigned int)time(NULL));

   for (i=0; i<MAX_TRY; i++) {
      n = rand() % 365;       /* Generate a random birthday */
      printf("%2d. ",i+1);    /* Generate the loop number */
      printDate(n);           /* Print the date in the standard format */
      checkMatch(i,n,bday);   /* Check if this birthday has been previously
                                 generated. If yes, report and exit, else
                                 store it for future comparisons. */
   }
   printf("OOPS! No matches found among %d birthdays. Bad luck! Try again.\n",MAX_TRY);
}


[Course home] [Home]