Here's the idea:
Code:
#include <stdio.h>
#include <stdlib.h>
struct monthData
{
char *monthName;
int monthDays;
};
static const struct monthData MD[] =
{
{"January",31},
{"February",28},
{"March",31},
{"April",30},
{"May",31},
{"June",30},
{"July",31},
{"August",31},
{"September",30},
{"October",31},
{"November",30},
{"December",31},
};
int main ( void )
{
FILE *outputFile;
int day_code = 0,
days_in_month = 0,
leap_year = 0,
day,
month;
outputFile = fopen ( "dataout.txt", "w" );
if ( outputFile == NULL ) {
perror ( "File open error: outputFile" );
return EXIT_FAILURE;
}
do {
printf ("Enter day and leap year codes: ");
scanf ("%d%d", &day_code, &leap_year);
} while (day_code < 0 || day_code > 6 );
for (month = 0; month < 12; month++) {
fprintf ( outputFile, "\n\n%s", MD[month].monthName );
if ( month == 1 )
/* Check for February and leap year */
days_in_month = leap_year ? MD[month].monthDays + 1 : MD[month].monthDays;
else
days_in_month = MD[month].monthDays;
/* Calculate and write one month to file */
fprintf(outputFile, "\n\nSun Mon Tue Wed Thu Fri Sat\n");
for (day =1; day <= 1 + day_code * 5; day++) {
fprintf(outputFile, " ");
for ( day = 1; day <= days_in_month; day++) {
fprintf(outputFile, "%2d", day);
if ( (day + day_code) % 7 > 0 )
fprintf(outputFile, " ");
else
fprintf(outputFile, "\n");
}
day_code = (day_code + days_in_month) % 7;
}
}
return 0;
}
I also implemented a method that would make your program a bit shorter and easier to follow by removing the long switch statement. I used the option of placing the month name and number of days in an array of structs, but this method would also work with two arrays; one holding the names and one holding the days.
-Prelude