Hi,
I did an c program exercise where I enter a date in format DD MM YYYY (eg. 31 12 2003) to output 31st December 2003. Restrictions at this stage in the book I am reading are: no strings, loops or functions.
After accepting the input, I check the date format is correct and check for leap days. If that is ok, I then use 2 switches to append "st, nd, rd, th" to the day and substitute the month name for the month number and finally print out the year. Here is my code. I feel that it is long winded and could be optimized. Care to criticize my code? Maybe the switch could be improved, ie is possible to have 1st 21st and 31st all on 1 line?
Code:
int main(void)
{
int day = 0; /* capture user input day, month, year */
int month = 0;
int year = 0;
bool isLeapYear = 0; /* check for leap day */
bool validDate = 1; /* flag for processing output */
/* user input */
printf("\nEnter a date in the format DD MM YYYY. eg 31 12 2003\n> ");
scanf("%d %d %d", &day, &month, &year);
/* validate entry */
if ( ((day<1)||(day>31)) || ((month<1)||(month>12)) || (year<1))
{
printf("Sorry invalid date entry.\n");
validDate = 0;
}
/* check day entered against the 5 months do not exceed 30 days */
else if ( (((month==4)||(month==6)||(month==9)||(month==11)) && (day>30))
|| (month==2)&&(day>29))
{
printf("\nInvalid day %d for month %d.\n", day, month);
validDate = 0;
}
else if ((month==2)&&(day==29)) /* check if leap year */
{
isLeapYear = ( ((year%4==0)&&(year%100 != 0)) || (year%400 == 0));
if (!isLeapYear)
{
printf("\nInvalid day %d for non leap year %d.\n", day, year);
validDate = 0;
}
}
if(validDate) /* date entry is correct proceed with internal processing */
{
printf("Date in long format is: %d",day);
switch(day) /* print date postfix */
{
case 1:
printf("st");
break;
case 2:
printf("nd");
break;
case 3:
printf("rd");
break;
case 21:
printf("st");
break;
case 22:
printf("nd");
break;
case 23:
printf("rd");
break;
case 31:
printf("st");
break;
default:
printf("th");
break;
}
switch(month) /* print month */
{
case 1:
printf(" January");
break;
case 2:
printf(" February");
break;
case 3:
printf(" March");
break;
case 4:
printf(" April");
break;
case 5:
printf(" May");
break;
case 6:
printf(" June");
break;
case 7:
printf(" July");
break;
case 8:
printf(" August");
break;
case 9:
printf(" September");
break;
case 10:
printf(" October");
break;
case 11:
printf(" November");
break;
case 12:
printf(" December");
break;
default:
printf("<undefined month>");
break;
}
printf(" %d.\n\n", year); /* print year */
}
return 0;
}
/*
Output:
Enter a date in the format DD MM YYYY. eg 31 12 2003
> 1 12 2009
Date in long format is: 1st December 2009.
*/