C++ Program to Calculate Difference Between Two Time Periods Using Structure

In this C++ program, we will find the difference between two time periods using a user defined structure. A time period is uniquely defined as triplets of hours, minutes and seconds.
For Example : 2 hour 20 minutes and 10 seconds.

Points to remember about Structures in C++
  • Keyword struct is used to declare a structure.
  • Structure in C++ programming language is a user defined data type that groups logically related information of different data types into a single unit.
  • We can declare any number of member variables inside a structure.
  • We can access the member of structure either using dot operator(.) or arrow operator(->) in case of structure pointer.

To store a time period we will define a user defined structure "Time" having three member variables hour, mins and secs.

struct Time {
  int hour;
  int mins;
  int secs;
};

We will use variables of structure Time, to time periods.


C++ Program to Calculate Difference Between Two Time Periods

#include <iostream>
using namespace std;

struct Time {
  int hour;
  int mins;
  int secs;
};

Time findTimeDifference(Time t1, Time t2);

int main() {
    Time t1, t2, diff;
    
    cout << "Enter earlier time in hours, minutes and seconds\n";
    cin >> t1.hour >> t1.mins >> t1.secs;

    cout << "Enter current time in hours, minutes and seconds\n";
    cin >> t2.hour >> t2.mins >> t2.secs;
    
    diff = findTimeDifference(t1, t2);

    cout << "Difference = "<< diff.hour << ":" 
        << diff.mins << ":" << diff.secs;
    return 0;
}

Time findTimeDifference(Time t1, Time t2){
 Time diff;
    if(t2.secs > t1.secs){
        --t1.mins;
        t1.secs += 60;
    }

    diff.secs = t1.secs - t2.secs;
    if(t2.mins > t1.mins) {
        --t1.hour;
        t1.mins += 60;
    }
    
    diff.mins = t1.mins-t2.mins;
    diff.hour = t1.hour-t2.hour;
    
    return diff;
}
Output
Enter earlier time in hours, minutes and seconds
5 15 40
Enter current time in hours, minutes and seconds
2 40 14
Difference = 2:35:26

In this program, we take two Time periods as input from user in the form of hours, minutes and seconds and store in structure variable t1 and t2. To find the difference between t1 and t2, we call "findTimeDifference" function by passing t1 and t2. Finally, we display the difference of time periods in screen using cout.


Recommended Posts
C++ Program to Add Two Distances in Inch and Feet
C++ Program to Add Two Complex Numbers Using Structure
C++ Program to Store Information of an Employee in Structure
C++ Program to Print Pascal Triangle
C++ Program to Print Floyd Triangle
C++ Program to Multiply Two Numbers Using Addition
C++ Program to Find Largest Element of an Array
C++ Program to Find Sum of Natural Numbers Using Recursion
C++ Program to Display Factors of a Number
All C++ Programs