Mathematics 1201: Programming in C Solutions to Reading and Homework Assignment #4 Prof. Wickerhauser Chapter 4 Exercises: Exercise 9, p.100 Program: int IsLeap( int Year ) { if( Year % 4 == 0 ) /* divisible by 4... */ if( Year % 100 != 0 /* ...and not divisible by 100... */ || Year % 400 == 0 ) /* ...unless also divisible by 400 */ return 1; /* Leap Year! */ return 0; /* Not a leap year. */ } Exercise 10, p.101 Program: #define FAIL return 0 #define SUCCEED return 1 #define JAN 1 #define FEB 2 #define MAR 3 #define APR 4 #define MAY 5 #define JUN 6 #define JUL 7 #define AUG 8 #define SEP 9 #define OCT 10 #define NOV 11 #define DEC 12 int IsLeap ( int Year ); /* Prototype of Exercise 9 function */ int DaysIn( int Month, int Year ) { switch(Month) { case JAN: case MAR: case MAY: case JUL: case AUG: case OCT: case DEC: return 31; case APR: case JUN: case SEP: case NOV: return 30; break; case FEB: if( IsLeap(Year) ) return 29; else return 28; } return -1; /* Month is not 1,2,...,12 */ } int IsActualDate( int Month, int Day, int Year ) { /* Test for problems; quit and return 0 at the first one */ if( Year<1600 || Year>2500 ) FAIL; if( Month<1 || Month>12 ) FAIL; /* not actually necessary */ if( Day<1 || Day>DaysIn( Month, Year) ) FAIL; SUCCEED; } Exercise 11, p.101 Program: int IsLeap ( int Year ); /* Prototype of Exercise 9 function */ int DaysIn( int Month, int Year ); /* Prototype of Ex. 10 function #1 */ int IsActualDate( int Month, int Day, int Year ); /* Ex. 10 function #2 */ int ElapsedDays( int Month, int Day, int Year ) { /* Time in days since Dec 31, 1599 */ int y, m, days; if ( !IsActualDate(Month, Day, Year) ) return -1; /* indicates unreasonable inputs */ days = Day; /* count the excess days */ for( m=1; m int IsLeap ( int Year ); /* Prototype of Exercise 9 function */ int DaysIn( int Month, int Year ); /* Prototype of Ex. 10 function #1 */ int IsActualDate( int Month, int Day, int Year ); /* Ex. 10 function #2 */ int ElapsedDays( int Month, int Day, int Year ); /* Ex. 11 function */ #define COMPLAIN {printf("Date is out of range.\n"); return 1;} int main( void ) { /* Time in days between two dates since Dec 31, 1599 */ int d1, m1, y1, d2, m2, y2, ed1, ed2; /* Prompt for two dates: */ printf("Enter the first date like `mm dd yyyy': "); scanf( "%d %d %d", &m1, &d1, &y1 ); ed1 = ElapsedDays(m1, d1, y1 ); /* returns -1 on bad inputs */ if ( ed1<0 ) COMPLAIN; printf("Enter the second date like `mm dd yyyy': "); scanf( "%d %d %d", &m2, &d2, &y2 ); ed2 = ElapsedDays(m2, d2, y2 ); /* returns -1 on bad inputs */ if ( ed2<0 ) COMPLAIN; if( ed1==ed2 ) printf("The two dates are identical.\n"); else if( ed1ed2 */ printf("First date follows second by %d days.\n", ed1-ed2); return 0; }