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



  1. //C program to calculate difference between two time periods
  2. #include <stdio.h>
  3. struct Time
  4. {
  5. int secs;
  6. int mins;
  7. int hours;
  8. };
  9. void difference(struct Time t1, struct Time t2, struct Time *diff);
  10. int main()
  11. {
  12. struct Time startTime, stopTime, diff;
  13. printf("Please enter start time: \n");
  14. printf("Enter hours, minutes and seconds respectively: ");
  15. scanf("%d %d %d", &startTime.hours, &startTime.mins, &startTime.secs);
  16. printf("Please enter stop time: \n");
  17. printf("Enter hours, minutes and seconds respectively: ");
  18. scanf("%d %d %d", &stopTime.hours, &stopTime.mins, &stopTime.secs);
  19. difference(startTime, stopTime, &diff);
  20. printf("\nTIME DIFFERENCE: %d:%d:%d - ", startTime.hours, startTime.mins, startTime.secs);
  21. printf("%d:%d:%d ", stopTime.hours, stopTime.mins, stopTime.secs);
  22. printf("= %d:%d:%d\n", diff.hours, diff.mins, diff.secs);
  23. return 0;
  24. }
  25. void difference(struct Time start, struct Time stop, struct Time *diff)
  26. {
  27. if(stop.secs > start.secs){
  28. --start.mins;
  29. start.secs += 60;
  30. }
  31. diff->secs = start.secs - stop.secs;
  32. if(stop.mins > start.mins){
  33. --start.hours;
  34. start.mins += 60;
  35. }
  36. diff->mins = start.mins - stop.mins;
  37. diff->hours = start.hours - stop.hours;
  38. }

Output


Output!