1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
#include <iostream>
int main()
{
// Suppose that the first day of the month is a Saturday.
// invariant: the first day of an unknown month is a saturday
// Write a program that gets the number (Day date) of the day in that month
// invariant: the day entered by the user is a valid day in the same (unknown) month
std::cout << "enter day: " ;
unsigned int day ;
std::cin >> day ;
// no matter what this unknown month is, day can't be zero, and it can't be more than 31
if( day == 0 || day > 31 ) std::cerr << "invalid day\n" ;
else // we assume that the day entered by the user is a valid day in this particular month
{
// we know that 1, 8, 15, 22 and 29 are saturdays (SamuelAdams)
// therefore we know that 2, 9, 16, 23 and 30 are sundays
// therefore we know that 3, 10, 17, 24 and 31 are mondays
// etc.
// if we divide 'day' by 7, the remainder would be
// 1 for a saturday, 2 for a sunday, 3 for a monday, 4 for a tuesday ... 0 for a friday
switch( day % 7 ) // assuming that we haven't come across arrays as yet
{
case 1 : std::cout << "saturday\n" ; break ;
case 2 : std::cout << "sunday\n" ; break ;
case 3 : std::cout << "monday\n" ; break ;
case 4 : std::cout << "tuesday\n" ; break ;
case 5 : std::cout << "wednesday\n" ; break ;
case 6 : std::cout << "thursday\n" ; break ;
case 0 : std::cout << "friday\n" ;
}
}
}
|