Answer to Question #48427 in C++ for anu

Question #48427
Write a C++ program to create a class called DATE. Accept two valid dates in the form dd/mm/yyyy. Implement the following operations by overloading the operators + and -. After every operation show the results by overloading the operator <<:
a) ndays = d1 – d2; where d1 and d2 are DATE objects, d1>=d2 and ndays is an
integer.
b) d2 = d1 + ndays; where d1 is a DATE object and ndays is an integer.
1
Expert's answer
2014-11-03T00:41:03-0500
#include <stdlib.h>
#include <iostream>
#include <stdio.h>
#include <cstdlib>
using namespace std;
//array that stores the number of days for each month of non-leap year
const int DAYSINMONTH[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
class Date
{
private:
int dd;
int mm;
int yy;
bool leapOrNot;
public:
Date (int _dd, int _mm, int _yy)
{
dd = _dd; mm = _mm; yy = _yy;
CheckLeap();
}
int Days(int _dd, int _mm,int _yy)
{
int days = 0;
int leap;
if ((_yy % 4 == 0 && _yy % 100 != 0) || (_yy % 100 == 0 && _yy % 400 == 0)) leap = true;
else
leap = false;
while(_mm > 0)
{
days += DAYSINMONTH[_mm-1];
--_mm;
}
if (leap) days += 1;
--_yy;
while (_yy > 0)
{
if ((_yy % 4 == 0 && _yy % 100 != 0) || (_yy % 100 == 0 && _yy % 400 == 0)) leap = true;
else
leap = false;
if (leap) days += 366;
else
days += 365;
--_yy;
}
days += _dd;
return days;
}
void CheckLeap()
{
if ((yy % 4 == 0 && yy % 100 != 0) || (yy % 100 == 0 && yy % 400 == 0)) leapOrNot = true;
else
leapOrNot = false;
}
Date Date:: operator +(int ndays);
int Date::operator -(Date t);
void DisplayDate()
{
cout<<dd<<"/"<<mm<<"/"<<yy<<endl;
}
};
int main()
{
int dd, mm, yy;
cout<<"Enter the first date (dd, mm, yyyy) : ";
cin>>dd>>mm>>yy;
Date d1(dd, mm, yy);
cout<<"Enter the second date (dd, mm, yyyy) : ";
cin>>dd>>mm>>yy;
Date d2(dd, mm, yy);
int ndays;
ndays = d1 - d2;
cout<<endl<<endl<<"ndays = d1 "<<'-'<<" d2 = "<<ndays<<endl;
d2 = d1 + ndays;
cout<<"d2 = d1 + ndays = ";
d2.DisplayDate();

cout<<endl;
system("pause");
return 0;
}
Date Date::operator +(int ndays)
{
Date date(dd,mm, yy);
date.dd += ndays;
while ( date.dd > DAYSINMONTH[ date.mm-1])
{
if ( date.leapOrNot && date.mm == 2)
{
date.dd -= 29;
++ date.mm;
}
else
{
date.dd -= DAYSINMONTH[ date.mm-1];
++date.mm;
}
if ( date.mm > 12)
{
++ date.yy; date.mm = 1;
date.CheckLeap();
}
}
return date;
}
int Date::operator -(Date t)
{
int x1 = Days(dd, mm, yy);
int x2 = Days(t.dd, t.mm, t.yy);
return x1 - x2 + 1;
}


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS