|
Solution of Assignment 2 |
You can compute the date for any Easter Sunday from 1982 to 2048 as follows (all variables are of type int):
a is year % 19
b is year % 4
c is year % 7
d is (19 * a + 24) % 30
e is (2 * b + 4 * c + 6 * d + 5) % 7
Easter Sunday is March (22 + d + e)
Note that 22 + d + e can be greater than 31 (it is between 0 and 57). This means the formula can give a date in April. Keep this in mind.
Write a program to read in a year (entered as a 4-digit int). If the year entered is between 1982 and 2048, then the program should display the date of the Easter in the format mentioned below. If the year entered is not between 1982 and 2048, then the program should display "Invalid Input".
Here is a sample run. The format of the input and output of your program must look exactly the same as the format of the input and output in the sample run.
Enter the year in a four-digit format (for example, 2002): 1985
Easter is Sunday, April 7, 1985.
Solution: #include
<iostream>
#include <string>
using namespace std;
int main()
{
int year, a, b, c, d, e, day;
string month = "March";
cout << "Enter the year in a four-digit format (for example, 2002): ";
cin >> year;
// Check if the year is in the range
if ((year >= 1982) && (year <= 2048))
{
a = year % 19;
b = year % 4;
c = year % 7;
d = (19 * a + 24) % 30;
e = (2 * b + 4 * c + 6 * d + 5) % 7;
day = 22 + d + e;
// If day > 31 change month to April and correct day.
if (day > 31)
{
day = day % 31;
month = "April";
}
// Display result
cout << endl;
cout << "Easter is Sunday, " << month << " " << day << ", " << year << "." << "\n\n";
}
else // year is not in the range
cout << endl << "Invalid Year (must be between 1982 and 2048)." << "\n\n";
return 0;
}
|