#include <stdio.h>
// Define a structure to represent time
struct Time {
int hours;
int minutes;
int seconds;
};
// Function to calculate the difference between two time periods
void calculateTimeDifference(struct Time t1, struct Time t2, struct Time *difference) {
int seconds1, seconds2, diff_seconds;
// Convert both times to seconds
seconds1 = t1.hours * 3600 + t1.minutes * 60 + t1.seconds;
seconds2 = t2.hours * 3600 + t2.minutes * 60 + t2.seconds;
// Calculate the difference in seconds
diff_seconds = seconds1 - seconds2;
// Convert the difference in seconds back to hours, minutes, and seconds
difference->hours = diff_seconds / 3600;
difference->minutes = (diff_seconds % 3600) / 60;
difference->seconds = diff_seconds % 60;
}
int main() {
struct Time startTime, endTime, timeDifference;
// Input start time
printf("Enter the start time (hours minutes seconds): ");
scanf("%d %d %d", &startTime.hours, &startTime.minutes, &startTime.seconds);
// Input end time
printf("Enter the end time (hours minutes seconds): ");
scanf("%d %d %d", &endTime.hours, &endTime.minutes, &endTime.seconds);
// Calculate the time difference
calculateTimeDifference(startTime, endTime, &timeDifference);
// Display the time difference
printf("Time Difference: %02d:%02d:%02d\n", timeDifference.hours, timeDifference.minutes, timeDifference.seconds);
return 0;
}
In this program, we use a structure Time
to represent a time period with three components: hours
, minutes
, and seconds
.
The calculateTimeDifference
function takes two Time
structures (for the start and end times) and a pointer to a Time
structure (to store the difference). It calculates the difference in seconds and then converts it back to hours, minutes, and seconds.
In the main
function, we:
Input the start time and end time from the user.
Call the
calculateTimeDifference
function to compute the difference between the two times.Display the calculated time difference in the format HH:MM:SS.
Here's an example of how the program works:
Enter the start time (hours minutes seconds): 10 15 30
Enter the end time (hours minutes seconds): 12 30 45
Time Difference: 02:15:15
In this example, the program calculates the time difference between
10:15:30 and 12:30:45, and the result is 2 hours, 15 minutes, and 15
seconds.