Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a C++ program which contains a class named Time having three datamembers .

ID: 3607977 • Letter: W

Question

Write a C++ program which contains a class namedTime having three datamembers.

The class must have

·        Adefault and parameterizedconstructor

·       show() method to display the time in proper formatlike HH:MM:SS on the screen

·       get() method to get time from user

·        OverloadedPlus (+) and Minus (-)operators

·        Adestructor

  

You will overload + and - operator for this class.

In main program make 3 objects of the Timeclass time1, time2 andtime3 and call the get()functions for time1 and time2 then perform time3 = tim1+time2 andthen you will display time3 using its show()function.

Note1: While Adding the time keep in mind do not just add thehours into hours and minutes into minutes and seconds in seconds ,e.g

10:25:10

+01:45:25

---------------------

11: 70: 35

Will not be correct, instead your code should add times like,Note that as number of minutes have increased 60, hour have beenincreased.

10:25:10

+ 01:45:25

-------------------

12: 10: 35

Explanation / Answer

#include<iostream>

using namespace std;

class Time{

public:

int hr,min,sec;

Time(){

hr=min=sec=0;

}

Time(int h,int m,int s)

{

hr=h;

min=m;

sec=s;

}

Time operator + ( Time t)

{

int h,m,s;

int sum;

sum = (hr + t.hr)*3600 + (min + t.min)*60 + sec +t.sec;

s = sum %60;

sum = sum/60;

m = sum % 60;

h = sum/60;

return Time(h,m,s);

}

void get()

{

cout<<" Enter hrs:";

cin>>hr;

cout<<"Enter min:";

cin>>min;

cout<<"Enter sec:";

cin>>sec;

}

Time operator - ( Time t)

{

int h,m,s;

int sum1,sum2,sum;

sum1 = (hr)*3600 + (min )*60 + sec ;

sum2 = (t.hr)*3600 + (t.min)*60 +t.sec;

if(sum1>sum2)

sum = sum1-sum2;

else

sum = sum2-sum1;

s = sum %60;

sum = sum/60;

m = sum % 60;

h = sum/60;

return Time(h,m,s);

}

void show()

{

cout<<"Time is"<<hr<<":"<<min<<":"<<sec<<endl;

}

};

int main()

{

Time t1;

Time t2;

cout<<"Enter first time:";

t1.get();

cout<<"Enter second time:";

t2.get();

Time t_sum = t1 + t2;

Time t_diff = t1 - t2;

cout<<"Sum ";

t_sum.show();

cout<<"Diff ";

t_diff.show();

system("pause");

}

/* Sample output

Enter first time:

Enter hrs:10

Enter min:25

Enter sec:10

Enter second time:

Enter hrs:1

Enter min:45

Enter sec:25

Sum Time is 12:10:35

Diff Time is 8:39:45

Press any key to continue . ..

*/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote