MIT-Curricular/DS/C/Lab/Week2/timehandler.c

69 lines
1.5 KiB
C

#include <stdio.h>
typedef struct {
int hour;
int min;
int sec;
} Time;
void read_time(Time *t) {
scanf("%d %d %d", &t->hour, &t->min, &t->sec);
}
void display_time(Time t) {
printf("%02d:%02d:%02d\n", t.hour, t.min, t.sec);
}
Time add_time(Time t1, Time t2) {
Time result;
result.sec = t1.sec + t2.sec;
result.min = t1.min + t2.min + result.sec / 60;
result.sec %= 60;
result.hour = t1.hour + t2.hour + result.min / 60;
result.min %= 60;
result.hour %= 24;
return result;
}
Time diff_time(Time t1, Time t2) {
Time result;
int total_sec1 = t1.hour * 3600 + t1.min * 60 + t1.sec;
int total_sec2 = t2.hour * 3600 + t2.min * 60 + t2.sec;
int diff_sec = total_sec1 - total_sec2;
if (diff_sec < 0) {
diff_sec += 24 * 3600;
}
result.hour = diff_sec / 3600;
result.min = (diff_sec % 3600) / 60;
result.sec = diff_sec % 60;
return result;
}
int main() {
Time t1, t2, sum, difference;
printf("Enter the first time (hours minutes seconds): ");
read_time(&t1);
printf("Enter the second time (hours minutes seconds): ");
read_time(&t2);
printf("First time: ");
display_time(t1);
printf("Second time: ");
display_time(t2);
sum = add_time(t1, t2);
printf("Sum of times: ");
display_time(sum);
difference = diff_time(t1, t2);
printf("Difference between times: ");
display_time(difference);
return 0;
}