C Program to Calculate Difference Between Two Time Periods
This program will read two times in HH:MM:SS using structure and calculate difference of entered times
- //C program to calculate difference between two time periods
- #include <stdio.h>
- struct Time
- {
- int secs;
- int mins;
- int hours;
- };
- void difference(struct Time t1, struct Time t2, struct Time *diff);
-
- int main()
- {
- struct Time startTime, stopTime, diff;
-
- printf("Please enter start time: \n");
- printf("Enter hours, minutes and seconds respectively: ");
- scanf("%d %d %d", &startTime.hours, &startTime.mins, &startTime.secs);
-
- printf("Please enter stop time: \n");
- printf("Enter hours, minutes and seconds respectively: ");
- scanf("%d %d %d", &stopTime.hours, &stopTime.mins, &stopTime.secs);
-
- difference(startTime, stopTime, &diff);
-
- printf("\nTIME DIFFERENCE: %d:%d:%d - ", startTime.hours, startTime.mins, startTime.secs);
- printf("%d:%d:%d ", stopTime.hours, stopTime.mins, stopTime.secs);
- printf("= %d:%d:%d\n", diff.hours, diff.mins, diff.secs);
-
- return 0;
- }
-
- void difference(struct Time start, struct Time stop, struct Time *diff)
- {
- if(stop.secs > start.secs){
- --start.mins;
- start.secs += 60;
- }
-
- diff->secs = start.secs - stop.secs;
- if(stop.mins > start.mins){
- --start.hours;
- start.mins += 60;
- }
-
- diff->mins = start.mins - stop.mins;
- diff->hours = start.hours - stop.hours;
- }
Output
