BCA
Object Oriented Programming using C++ Practical
Madras University
Program 5
Design a class representing time in hh:mm:ss. Write functions to
a. Set and show the time
b. Find the difference between two time objects
c. Adding a given duration to a time
d. Conversion of the time object to seconds
SOURCE CODE:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
class Time {
private:
int hours;
int minutes;
int seconds;
public:
// Constructor to initialize time
Time(int h = 0, int m = 0, int s = 0) : hours(h), minutes(m), seconds(s) {}
// Function to set the time
void setTime(int h, int m, int s) {
hours = h;
minutes = m;
seconds = s;
}
// Function to show the time
void showTime() const {
cout << setw(2) << setfill('0') << hours << ":"
<< setw(2) << setfill('0') << minutes << ":"
<< setw(2) << setfill('0') << seconds << endl;
}
// Function to find the difference between two time objects
Time difference(const Time &t) const {
int totalSec1 = hours * 3600 + minutes * 60 + seconds;
int totalSec2 = t.hours * 3600 + t.minutes * 60 + t.seconds;
int diff = abs(totalSec1 - totalSec2);
int h = diff / 3600;
diff %= 3600;
int m = diff / 60;
int s = diff % 60;
return Time(h, m, s);
}
// Function to add a given duration to a time
void addDuration(int h, int m, int s) {
int totalSec = hours * 3600 + minutes * 60 + seconds + h * 3600 + m * 60 + s;
hours = (totalSec / 3600) % 24;
totalSec %= 3600;
minutes = (totalSec / 60) % 60;
seconds = totalSec % 60;
}
// Function to convert the time object to seconds
int toSeconds() const {
return hours * 3600 + minutes * 60 + seconds;
}
};
int main() {
Time t1(2, 45, 30);
Time t2(5, 50, 15);
int h,m,s;
cout << "Time 1: ";
t1.showTime();
cout << "Time 2: ";
t2.showTime();
Time diff = t1.difference(t2);
cout << "Difference: ";
diff.showTime();
cout<<"Enter Hours, minutes and seconds to add to time 1:";
cin>>h>>m>>s;
t1.addDuration(h,m,s);
cout << "Time 1 after adding given duration: ";
t1.showTime();
int seconds = t1.toSeconds();
cout << "Time 1 in seconds: " << seconds << endl;
return 0;
}
OUTPUT:
Time 1: 02:45:30
Time 2: 05:50:15
Difference: 03:04:45
Enter Hours, minutes and seconds to add to time 1:2 60 30
Time 1 after adding given duration: 05:46:00
Time 1 in seconds: 20760
Explanation:
- Constructor: Initializes the time with given hours, minutes, and seconds.
- setTime: Sets the time.
- showTime: Displays the time in hh:mmformat.
- difference: Calculates the absolute difference between two time objects and returns the result as a new
Time
object. - addDuration: Adds a given duration to the time object and adjusts for overflow in hours, minutes, and seconds.
- toSeconds: Converts the time to the total number of seconds since 00:00:00.
No comments:
Post a Comment