Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to calculate difference between given Time

C Code Example — Structure Programs

ADVERTISEMENT

C Program to calculate difference between given Time

Objective

Write a C program to calculate the difference between two Time periods.

Algorithm / Approach

  1. Define struct TIME with hours (h), minutes (m), and seconds (s).
  2. Read a Start Time (t1) and Stop Time (t2).
  3. Pass them to a Difference() function. The result is passed as a pointer (*differ).
  4. In the function, if t2.s > t1.s, borrow 1 minute: decrement t1.m and add 60 to t1.s.
  5. Subtract seconds: differ->s = t1.s - t2.s.
  6. Repeat the borrow logic for minutes if t2.m > t1.m (borrow 1 hour).
  7. 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)
ADVERTISEMENT