c
  1. c-program-to-calculate-difference-between-two-time-periods

Program to calculate difference between two time periods - (C Programs)

In this tutorial, we will create a C program to calculate the difference between two time periods. The program will take input from the user in the form of two time periods and will output the difference between them.

Syntax:

The syntax of the program is as follows:

#include<stdio.h>

int main()
{
    int hour1, min1, sec1, hour2, min2, sec2;
    int time1, time2, timediff;

    // Input first time period
    printf("Enter first time period:\n");
    printf("Hours? ");
    scanf("%d", &hour1);
    printf("Minutes? ");
    scanf("%d", &min1);
    printf("Seconds? ");
    scanf("%d", &sec1);

    // Input second time period
    printf("\nEnter second time period:\n");
    printf("Hours? ");
    scanf("%d", &hour2);
    printf("Minutes? ");
    scanf("%d", &min2);
    printf("Seconds? ");
    scanf("%d", &sec2);

    // Calculate time in seconds
    time1 = hour1 * 3600 + min1 * 60 + sec1;
    time2 = hour2 * 3600 + min2 * 60 + sec2;

    // Calculate time difference
    if(time1 > time2)
        timediff = time1 - time2;
    else
        timediff = time2 - time1;

    // Convert time difference to hours, minutes and seconds
    hour1 = timediff / 3600;
    min1 = (timediff - hour1 * 3600) / 60;
    sec1 = timediff - hour1 * 3600 - min1 * 60;

    // Output time difference
    printf("\nTime difference: %d:%d:%d - ", hour2, min2, sec2);
    printf("%d:%d:%d ", hour1, min1, sec1);

    return 0;
}

Example:

Suppose, we have two time periods:

  • Time period 1: 3 hours, 12 minutes and 30 seconds
  • Time period 2: 1 hour, 30 minutes and 45 seconds

The output of the program would be:

Enter first time period:
Hours? 3
Minutes? 12
Seconds? 30

Enter second time period:
Hours? 1
Minutes? 30
Seconds? 45

Time difference: 1:30:45 - 1:41:45

Explanation:

The program takes input from the user in the form of two time periods. The user is asked to enter the hours, minutes and seconds for both time periods. The program then calculates the time difference in seconds and converts it back to hours, minutes and seconds. Finally, the program outputs the time difference between the two time periods.

Use:

This program can be used to calculate the difference between two time periods. It is particularly useful in time-based applications such as games, sports and timing applications.

Summary:

In this tutorial, we created a C program to calculate the difference between two time periods. We covered the syntax, example, explanation, use and summary of the program. By using this program, you can easily calculate the time difference between any two time periods.

Published on: