in C++ Write a program that receives a date (e.g. 7 4 2008 for July 4, 2008) as
ID: 675456 • Letter: I
Question
in C++ Write a program that receives a date (e.g. 7 4 2008 for July 4, 2008) as input and outputs the day of the week that corresponds to that date. Write the function dayOfWeek that computes the weekday of a given date using a formula known as Zeller’s congruence:
h = (q +[(m+1)26/10]+Y+[Y/4]+6[Y/100]+[Y/400]) mod 7
where
· h is the day of the week (0 = Saturday, 1 = Sunday, 2 = Monday, ...)
· q is the day of the month
· m is the month (3 = March, 4 = April, 5 = May, ..., 14 = February)
· Y is the modified year, which is the current year for March through December, and the previous year for January and February.
NOTES: In this algorithm January and February are counted as months 13 and 14 of the previous year. For example, if the date passed to your function is February 2, 2010, the algorithm must interpret the date as the second day of the fourteenth month of 2009. The floor function is implemented via integer division.
The prototype for this function is: string dayOfWeek( int month, int day, int year);
Your function is allowed to call “helper” functions of your own design, if needed. You should also include any additional functions that will help to streamline the code within your main function.
Provide a program that tests your functions via a loop construct for acquiring testing data.
Example run (with user input indicated with bold italics):
Enter a date or Q to quit: 10 13 2011
Thursday, October 13, 2011
Enter a date or Q to quit: 4 14 1865
Friday, April 14, 1865
Enter a date or Q to quit: 2 29 2000
Tuesday, February 29, 2000
Enter a date or Q to quit: Q
Explanation / Answer
#include<iostream>
#include<string.h>
using namespace std;
string dayOfWeek( int month, int day, int year) {
int h = (day +((month+1)*26/10)+year+(year/4)+6*(year/100)+(year/400)) % 7;
switch (h) {
case 0:
return "Saturday";
break;
case 1:
return "Sunday";
break;
case 2:
return "Monday";
break;
case 3:
return "Tuesday";
break;
case 4:
return "Wednesday";
break;
case 5:
return "Thursday";
break;
case 6:
return "Friday";
break;
}
return "";
}
int main() {
string in;
int day, year, month;
while (true) {
cout<<"Enter a date or Q to quit: ";
cin>>in;
if(in == "Q") {
return 0;
}
month = stoi(in);
cin>>day>>year;
cout<<dayOfWeek(month, day, year)<<", ";
switch (month) {
case 1:
cout<<"January";
break;
case 2:
cout<<"February";
break;
case 3:
cout<<"March";
break;
case 4:
cout<<"April";
break;
case 5:
cout<<"May";
break;
case 6:
cout<<"June";
break;
case 7:
cout<<"July";
break;
case 8:
cout<<"August";
break;
case 9:
cout<<"September";
break;
case 10:
cout<<"October";
break;
case 11:
cout<<"November";
break;
case 12:
cout<<"December";
break;
default:
break;
}
cout<<" "<<day<<", "<<year<<" ";
return 0;
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.