Chapter 9 _________ Working with Structures 1-1 Prog 19.1: Illustrating a structure #include <stdio.h> int main (void) { struct date { int month; int day; int year; } // type declaration struct date today; today.month = 12; today.day = 17; today.year = 2008; printf (“Today’s date is %i/%i/%.2i.\n”, today.day, today.month, today.year); today.month = 1; today.day = 1; if (today.month == 5 && today.day == 17) printf(“Happy May 17th!\n”); return 0; } ___________________________________________ Today’s date is 17/12/2008. 1-2 Happy New Year! Prog 19.2 (A): Determining tomorrow’s date given today’s. #include <stdio.h> int main (void) { struct date { int month; int day; int year; } // type declaration const int daysPerMonth [13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; struct date today, tomorrow; printf (“Today’s date (dd mm yyyy): “); scanf (“%i%i%i”, &today.day, &today.month, &today.year); 1-3 Prog 9.2 (B): Determining tomorrow’s date given today’s. if (today.day != daysPerMonth [today.month]) { tomorrow.day = today.day + 1; tomorrow.month = today.month; tomorrow.year = today.year; } else if (today.month == 12) { tomorrow.day = 1; tomorrow.month = 1; tomorrow.year = today.year + 1; } else { tomorrow.day = 1; tomorrow.month = today.month + 1; tomorrow.year = today.year; } printf (“Tomorrow’s date is ” “%i/%i/%.2i.\n”, tomorrow.day, tomorrow.month, tomorrow.year); return 0; } ___________________________________________ Today’s date (dd mm yyyy): 20 12 2008 Tomorrow’s date is 20/12/2008. 1-4 Prog 19.3 (A): Revising: Find tomorrow’s date given today’s. #include <stdio.h> struct date {int month; int day; int year;}; int main (void) { struct date today, tomorrow; int numOfDays (struct date d) ; printf (“Today’s date (dd mm yyyy): “); scanf (“%i%i%i”, &today.day, &today.month, &today.year); if ( today.day != numOfDaysInMonth (today) ) { tomorrow.day = today.day + 1; tomorrow.month = today.month; tomorrow.year = today.year; } else if (today.month == 12) { tomorrow.day = 1; tomorrow.month = 1; tomorrow.year = today.year + 1; } else { tomorrow.day = 1; tomorrow.month = today.month + 1; tomorrow.year = today.year; } printf (“Tomorrow’s date is %i/%i/%i.\n”, tomorrow.day,tomorrow.month, tomorrow.year); return 0; } 1-5 Prog 19.3 (B): Revising: Find tomorrow’s date given today’s. int numOfDaysInMonth (struct date d) { int days; bool isLeapYear (struct date d); const int daysPerMonth [13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; if ( isLeapYear(d) && d.month == 2) days = 29; else days = daysPerMonth [d.month]; return days; } 1-6 Prog 19.3 (C): Revising: Find tomorrow’s date given today’s. bool isLeapYear (struct date d); bool aLeapYear = false; if ( (d.year % 4 == 0 && d.year % 100 != 0) ) || (d.year % 400 == 0 )) aLeapYear = true; return aLeapYear; } 1-7