Exercise:
Write a C++ program to calculate the difference between two time periods.
Click Here to View the Solution:
#include <iostream>
using namespace std;
struct time
{
int sec, min, hr;
};
void timeDiff(struct time, struct time, struct time *);
int main()
{
struct time diff, t1, t2;
cout << "Starting time" << endl;
cout << "Insert hours, minutes and seconds respectively:\n";
cin >> t1.hr >> t1.min >> t1.sec;
cout << "\nStoppage time" << endl;
cout << "Insert hours, minutes and seconds respectively:\n";
cin >> t2.hr >> t2.min >> t2.sec;
timeDiff(t1, t2, &diff);
cout << endl << "Time Difference: " << t1.hr << ":" << t1.min << ":" << t1.sec;
cout << " - " << t2.hr << ":" << t2.min << ":" << t2.sec;
cout << " = " << diff.hr << ":" << diff.min << ":" << diff.sec;
return 0;
}
void timeDiff(struct time t1, struct time t2, struct time *diff)
{
if(t2.sec > t1.sec)
{
--t1.min;
t1.sec += 60;
}
diff->sec = t1.sec - t2.sec;
if(t2.min > t1.min)
{
--t1.hr;
t1.min += 60;
}
diff->min = t1.min-t2.min;
diff->hr = t1.hr-t2.hr;
}
Click Here to View the Output:
Starting time Insert hours, minutes and seconds respectively: 5 32 16 Stoppage time Insert hours, minutes and seconds respectively: 2 42 6 Time Difference: 5:32:16 - 2:42:6 = 2:50:10
Click Here to View the Explanation:
- A structure
time
is created and a structure variablet1
andt2
is created. Some variables are initialized in the structureint
type:sec
,min
,hr
. - The user is requested to enter the
starting time
in hours, minutes, and seconds respectively. This information is saved in the structure variablet1
. - The user is requested to enter the
stoppage time
in hours, minutes and seconds respectively. This input is saved in the structure variablet2
. - A function
timeDiff
is created and called by reference in themain ()
function. - This function is used to calculate the time difference. The result is displayed on the screen.