/********************** 04-2-S.TXT ******************** *********** Prof. Dr. B. Bartning *********************/ - Remarks about solutions - ATTENTION, please, here are only program fragments, this file cannot be compiled as a whole!! - WITHOUT guarantee! - ************************************************************** 01 // multiple selection 02 // Program outputs the number of days of the month monthNumber 03 // in a non-leap year 04 #include 05 int main() 06 { 07 int monthNumber, numDays; 08 cin >> monthNumber; 09 switch (monthNumber) { 10 case 1: 11 case 3: 12 case 5: 13 case 7: 14 case 8: 15 case 10: 16 case 12: numDays=31; break; 17 case 4: 18 case 6: 19 case 9: 20 case 11: numDays=30; break; 21 case 2: numDays=28; break; 22 } 23 cout << numDays << endl; 24 return 0; 25 } ************************************************************ (a) Before 09: if (monthNumber < 1 || monthNumber > 12) cout << "Please, input only month numbers between 1 and 12!" << endl; else { After 23: } ATTENTION: in the ELSE branch ("else"), there must appear two statements (switch AND output "cout << numDays ..", because otherwise when wrong monthNumber, a non assigned value for numDays would be written. Therefore make a block with the brace pair { ... } ! ************************************************************ (b) 07new int monthNumber, yearNumber, numDays; 08new cin >> monthNumber >> yearNumber; 21new if (yearNumber%4==0) numDays=29; // leap year else numDays=28; or (AFTER explaination of (5.12)): numDays = (yearNumber%4==0) ? 29 : 28; (c) like (b), however: 21newnew if (yearNumber%4==0 && (yearNumber%100!=0 || yearNumber%400==0)) numDays=29; else numDays=28; Parentheses around the Or part (||) are necessary because Or has a lower precedence. ************************************************************ (d) Do it yourself! ************************************************************ (e) - here still WITHOUT a reading loop; loop see (5.26d) - Before 09: if (!cin) cout << "Please, input only digits!" << endl; else if (monthNumber < 1 || monthNumber > 12) cout << "Please, input only month numbers between 1 and 12!" << endl; else { After 23: } ************************************************************