Calculating the time difference between two periods is pretty common, both in life and programming. Say you have two times, like 2:45:50 and 1:20:30, and you wanna know how much time's passed between them. It's a useful calculation for keeping track of event durations or managing schedules.
We’ll write a C program to figure out the difference between two time periods given in hours, minutes, and seconds. Let’s check it out.
Prerequisites for the Time Difference Program in C
Before diving into the code, ensure you're familiar with the following.
- The
structkeyword for defining custom data types in C. - Basic arithmetic operations for handling time calculations.
- Input and output functions like
scanf()andprintf(). - Any C compiler such as GCC 9 or newer — or just run it in the EduSeekho online compiler.
Source Code of C Program to Calculate Difference Between Two Time Periods
Below is the source code for calculating the time difference.
#include <stdio.h>
struct Time {
int hours;
int minutes;
int seconds;
};
void calculateDifference(struct Time start, struct Time end, struct Time *diff) {
// Calculate seconds
if (end.seconds < start.seconds) {
--end.minutes;
end.seconds += 60;
}
diff->seconds = end.seconds - start.seconds;
// Calculate minutes
if (end.minutes < start.minutes) {
--end.hours;
end.minutes += 60;
}
diff->minutes = end.minutes - start.minutes;
// Calculate hours
diff->hours = end.hours - start.hours;
}
int main() {
struct Time startTime, endTime, diff;
// Input the start time
printf("Enter the first time period (HH MM SS):\n");
scanf("%d %d %d", &startTime.hours, &startTime.minutes, &startTime.seconds);
// Input the end time
printf("Enter the second time period (HH MM SS):\n");
scanf("%d %d %d", &endTime.hours, &endTime.minutes, &endTime.seconds);
// Calculate the difference
calculateDifference(startTime, endTime, &diff);
// Output the result
printf("Time difference: %d:%d:%d\n", diff.hours, diff.minutes, diff.seconds);
return 0;
}Try this code yourself — free
Run it in the EduSeekho online compiler. No setup needed.
Output of the Calculate Difference Between Two Time Periods Program
Here's what happens when you run the program and input the time values.
Enter the first time period (HH MM SS):
2 45 50
Enter the second time period (HH MM SS):
1 20 30
Time difference: 1:25:20
Algorithm to Calculate Difference Between Two Time Periods in C
The program calculates the difference by adjusting seconds and minutes as needed, then outputs the result. Here is the step-by-step logic.
- Read the first time period from the user.
- Read the second time period from the user.
- Calculate the difference in seconds, minutes, and hours.
- If the seconds are negative, adjust them and the minutes.
- If the minutes are negative, adjust them and the hours.
- Output the calculated time difference.
flowchart TD
A([Start]) --> B[Read first time period]
B --> C[Read second time period]
C --> D[Calculate differences in seconds, minutes, hours]
D --> E{"If seconds < 0?"}
E -->|Yes| F[Adjust seconds and minutes]
E -->|No| G[Next]
F --> G
G --> H{"If minutes < 0?"}
H -->|Yes| I[Adjust minutes and hours]
H -->|No| J[Next]
I --> J
J --> K[Output the time difference]
K --> L([End])How the C Program to Calculate Difference Between Two Time Periods Works
Let's walk through the code and explain each part.
- The code includes
<stdio.h>for standard input and output functions. - A
struct Timeis defined to group hours, minutes, and seconds. - The
calculateDifferencefunction computes the time difference by normalizing seconds and minutes. - In
main(),struct Timevariables are declared to hold the start, end, and difference times. - It prompts the user to enter the first and second time periods using
scanf(). - The
calculateDifferencefunction is called with the start and end times, and the result is stored indiff. - The program prints the time difference using
printf(). - The program returns
0, indicating successful execution.
Quick Quiz — test your understanding
Tap an option to check your answerWhat structure is used to store the time periods in this program?
Time and Space Complexity of the C Program to Calculate Time Difference
Let's analyze the efficiency of this program.
Time Complexity: O(1). The calculations involve a constant number of operations: comparing and adjusting hours, minutes, and seconds. This means the execution time doesn't scale with the input size, as shown by direct operations like diff->seconds = end.seconds - start.seconds.
Space Complexity: O(1). We only store a fixed number of variables: startTime, endTime, and diff, each with three integers for hours, minutes, and seconds. No extra space is required regardless of the input values.
Common mistake: Not adjusting hours, minutes, or seconds when borrowing for negative results can mess up your calculations.
Key takeaway: Structs are perfect for grouping time components, making your programs tidier and more organized.
FAQs About Calculating Time Differences in C
Here are some common questions that arise with this program.
Related Programs
If you found this program helpful, check out these related programs:
- C Program to Calculate Simple and Compound Interest
- C Program to Find the Roots of a Quadratic Equation
- C Program to Calculate Standard Deviation — Full Code & Output
- C Program to Check Leap Year with Code and Output
- C Program to Find the Area and Perimeter of a Rectangle
Conclusion
If you're often dealing with time calculations, using structs for your data makes everything easier to manage. Why not try extending this logic to handle days or even months next? It sets a good base for more complex scheduling programs.
Practice more with C language quizzes or run your own programs in our compiler.