WAP to create a class Time having members as hours, minutes and seconds . Initialize the object by using parameterized and copy constructor. Write the functions for addition and difference of Time objects.
#include <iostream>
using namespace std;
class Time{
//Data members should be hours, minutes and seconds.
int hours;
int minutes;
int seconds;
public:
//Set data members as zero in default constructor.
Time()
{
this->hours = 0;
this->minutes = 0;
this->seconds = 0;
}
//Take one object in main to set 23:24:59 hrs.
Time(int hours, int minutes, int seconds)
{
this->hours = hours;
this->minutes = minutes;
this->seconds = seconds;
}
void add_time()
{
this->seconds++;
if(this->seconds >= 60){
this->minutes ++;
this->seconds = this->seconds % 60;
}
if(this->minutes >= 60){
this->hours ++;
this->minutes = this->minutes % 60;
}
if(this->hours >= 24){
this->hours=0;
}
}
Time* computeTimeSum(Time t2){
Time* sumTime=new Time();
sumTime->seconds = this->seconds + t2.seconds;
sumTime->minutes = this->minutes + t2.minutes;
sumTime->hours = this->hours + t2.hours;
//implement mechanism to convert time in proper format
if(sumTime->seconds >= 60){
sumTime->minutes += sumTime->seconds / 60;
sumTime->seconds = sumTime->seconds % 60;
}
if(sumTime->minutes >= 60){
sumTime->hours += sumTime->minutes / 60;
sumTime->minutes = sumTime->minutes % 60;
}
return sumTime;
}
Time* computeTimeDifference(Time t2){
int totalSeconds1, totalSeconds2, differenceSeconds, tempMinutes;
totalSeconds1= (hours*3600)+(minutes*60)+seconds;
totalSeconds2= (t2.hours*3600)+(t2.minutes*60)+t2.seconds;
if(totalSeconds1>totalSeconds2){
differenceSeconds = totalSeconds1 - totalSeconds2;
}else{
differenceSeconds = totalSeconds2 - totalSeconds1;
}
Time* difference=new Time();
difference->seconds = differenceSeconds%60;
tempMinutes = differenceSeconds/60;
difference->minutes = tempMinutes%60;
difference->hours = difference->minutes/60;
return difference;
}
//Display time in the given format 23:24:59 hrs.
void display(){
cout<< this->hours << ":" << this->minutes << ":" << this->seconds<<" hrs";
}
};
int main(){
int hours,minutes,seconds;
cout << "Enter the first time (hours minutes seconds): ";
cin>> hours >> minutes >> seconds;
Time t1(hours, minutes, seconds);
t1.display();
cout << "\nEnter the second time (hours minutes seconds): ";
cin>> hours >> minutes >> seconds;
Time t2(hours, minutes, seconds);
t2.display();
cout<<"\n\nDifference time: ";
Time* differenceTime=t2.computeTimeDifference(t1);
differenceTime->display();
cout<<"\n\nSum time: ";
Time* sumTime=t2.computeTimeSum(t1);
sumTime->display();
delete differenceTime;
delete sumTime;
system("pause");
return 0;
}
Comments
Leave a comment