SOURCE CODE:
#include<iostream>
using namespace std;
class Time //class Time
{
private:
int hours;
int minutes; //member variables hours minutes seconds
int seconds;
public:
Time() //default constructer which sets all to 0
{
hours = 0;
minutes = 0;
seconds = 0;
}
Time(int h, int m, int s) //overloaded constructor which accepts hours minutes and seconds
{
hours = h;
minutes = m;
seconds = s;
}
void setTime(int h,int m,int s){ //setTime() methods which accepts hours minutes and seconds
hours = h;
minutes = m;
seconds = s;
}
void display() //display method which displays time in 11:59:59 format
{
if(hours<10) //if hours < 10 then add extra 0
cout<<"0"; //printing 0
cout<<hours<<":"; //printing hours
if(minutes<10) //if minutes <10 add extra 0
cout<<"0"; //printing 0
cout<<minutes<<":"; //printing minutes
if(seconds<10) //if seconds < 10 add extra 0
cout<<"0"; //printing 0
cout<<seconds<<endl; //printing seconds
}
void isValid(){ //isValid() methods which tells the time is valid or not
if(hours<0 || hours>23){
cout<<"Time is Invalid"<<endl;
}
else if(minutes<0 || minutes>59){
cout<<"Time is Invalid"<<endl;
}
else if(seconds<0 || seconds>59){
cout<<"Time is Invalid"<<endl;
}
else{
cout<<"Time is valid"<<endl;
}
}
void Increment(){ //Increment method which increments time by 1 seconds
seconds=seconds+1;
if(seconds>59){
seconds=0;
minutes=minutes+1;
}
if(minutes>59){
minutes=0;
hours=hours+1;
}
if(hours>23){
hours=0;
}
}
void Decrement(){ //Decrement() method which decrement time by 1 second
seconds=seconds-1;
if(seconds<0){
seconds=59;
minutes=minutes-1;
}
if(minutes<0){
minutes=59;
hours=hours-1;
}
if(hours<0){
hours=23;
}
}
Time AddTime(Time t1, Time t2) //AddTime method which adds two times
{
int finalHours = t1.hours + t2.hours;
int finalMinutes = t1.minutes + t2.minutes; //first add two hours minutes and seconds
int finalSeconds = t1.seconds + t2.seconds;
if (finalHours > 23) { //check if hour >23 if so then
finalHours -= 24;
}
if (finalMinutes > 59) { //check if minutes>59 if so then
finalMinutes -= 60;
finalHours += 1;
}
if (finalSeconds > 59) { //check if seconds>59 if so then
finalSeconds -= 60;
finalMinutes += 1;
}
Time t3(finalHours,finalMinutes ,finalSeconds);
return t3;
}
};
int main()
{
//testing code
Time t1(12,40,30);
t1.display();
t1.isValid();
Time t2(21,23,43);
t2.display();
t2.isValid();
Time t3=t1.AddTime(t1, t2);
t3.display();
return 0;
}
SCREENSHOT:
OUTPUT:
Get Answers For Free
Most questions answered within 1 hours.