Our teacher asked us to do this...
The algorithm to find which day of the week a given date falls upon is given below:
a = INT((14 - month) / 12)
y = year - a
m = month + (12 * a) - 2
dayIndx = (day + y + INT(y / 4) - INT(y / 100) + INT(y / 400) + INT(31 * m / 12)) MOD 7
eg. Given the date 06/07/1998, day = 06, month = 07 and year = 1998 in the above formula and dayIndx is the index of the days (for eg 0 -%26gt; Sunday, 1 -%26gt; Monday …… 6-%26gt;Saturday)
Using the above algorithm, write a program which takes as input a date and writes the corresponding day of the week for that date.
The first two characters of the input file will represent the day. The fourth and fifth characters will represent the month. The seventh, eighth, ninth, and tenth characters will represent the year. (The third and sixth characters will be “/”.)
How do i write this programme in C++????
C++ programming help?
I really should not have done the whole thing for you but I trust you are going to study and improve on the program and learn from it rather than hand it in as is. Also, you probably haven;t used istringstreams so if you cheat your teacher will catch you. Figure out how to do that portion differently on your own. Put in more edits.
#include %26lt;iostream%26gt;
#include %26lt;string%26gt;
#include %26lt;sstream%26gt;
using namespace std;
bool isValidDate(string date, int %26amp;dd, int %26amp;mm, int %26amp;yyyy)
{
if ((date.length() != 10)
|| (date[2] != '/')
|| (date[5] != '/')
|| (! isdigit(date[0]))
|| (! isdigit(date[1]))
|| (! isdigit(date[3]))
|| (! isdigit(date[4]))
|| (! isdigit(date[6]))
|| (! isdigit(date[7]))
|| (! isdigit(date[8]))
|| (! isdigit(date[9])))
return(false);
date[2] = ' ';
date[5] = ' ';
istringstream stream(date);
stream %26gt;%26gt; dd %26gt;%26gt; mm %26gt;%26gt; yyyy;
if ((mm %26lt; 0)
|| (mm %26gt; 12)
|| (dd %26lt; 0)
|| (dd %26gt; 31))
{
return(false);
}
//check for leap year and Feb end date
//if you want
return(true);
}
int getIndex(int dd, int mm, int yyyy)
{
int a = (14 - mm) / 12;
int y = yyyy - a;
int m = mm + (12 * a) - 2;
int index = (dd + y + (y / 4) - (y / 100) + (y / 400) + (31 * m / 12)) % 7;
return(index);
}
int main()
{
string days[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
string inDate;
int dd, mm, yyyy;
bool invalidDate = true;
while (invalidDate)
{
cout %26lt;%26lt; "\nEnter date (dd/mm/yyyy): ";
getline(cin, inDate);
if (isValidDate(inDate, dd, mm, yyyy))
invalidDate = false;
else
{
cout %26lt;%26lt; "\ninvalid date." %26lt;%26lt; endl;
continue;
}
cout %26lt;%26lt; inDate %26lt;%26lt; " was a " %26lt;%26lt; days[getIndex(dd, mm, yyyy)] %26lt;%26lt; endl;
}
return(0);
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment