C Program to calculate difference between given Time
Objective
Write a C program to calculate the difference between two Time periods.
Algorithm / Approach
- Define
struct TIMEwith hours (h), minutes (m), and seconds (s). - Read a Start Time (t1) and Stop Time (t2).
- Pass them to a
Difference()function. The result is passed as a pointer (*differ). - In the function, if
t2.s > t1.s, borrow 1 minute: decrementt1.mand add 60 tot1.s. - Subtract seconds:
differ->s = t1.s - t2.s. - Repeat the borrow logic for minutes if
t2.m > t1.m(borrow 1 hour). - Subtract hours.
main.c
#include<stdio.h>
struct TIME{
int s;
int m;
int h;
};
void Difference(struct TIME t1, struct TIME t2, struct TIME *diff);
int main( ){
struct TIME t1,t2,diff;
printf("Enter Start Time [hh:mm:ss]: ");
scanf("%d:%d:%d",&t1.h,&t1.m,&t1.s);
printf("Enter Stop Time [hh:mm:ss]: ");
scanf("%d:%d:%d",&t2.h,&t2.m,&t2.s);
Difference(t1,t2,&diff);
printf("TIME DIFFERENCE: ");
printf("%d:%d:%d\n",diff.h,diff.m,diff.s);
return 0;
}
void Difference(struct TIME t1, struct TIME t2, struct TIME *differ){
if(t2.s>t1.s){
--t1.m;
t1.s+=60;
}
differ->s=t1.s-t2.s;
if(t2.m>t1.m){
--t1.h;
t1.m+=60;
}
differ->m=t1.m-t2.m;
differ->h=t1.h-t2.h;
}
Expected Output
Enter Start Time [hh:mm:ss]: 2:23:46 Enter Stop Time [hh:mm:ss]: 1:13:46 TIME DIFFERENCE: 1:10:00
Explanation of the Program
- This program mimics how humans subtract time mathematically.
- If you need to subtract 45 seconds from 15 seconds, you can't get a negative number. You must "borrow" 1 minute (converting it to 60 seconds), making it 75 seconds. Then you can safely subtract 45 to get 30.
- By passing the result structure as a pointer, the function modifies the original variable in
main()directly.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)