Friday, 15 April 2016

C Program to Calculate Difference Between Two Time Period ( HH:MM:SS ) Using Structure

Problem :- C Program to Calculate Difference Between Two Time Period ( HH:MM:SS ) Using Structure

What Is Structure 

Structure is a user-defined data type in C which allows you to combine different data types to store a particular type of record. Structure helps to construct a complex data type in more meaningful way. It is somewhat similar to an Array. The only difference is that array is used to store collection of similar datatypes while structure can store collection of any type of data.

Structure is used to represent a record. Suppose you want to store record of Student which consists of student name, address, roll number and age. You can define a structure to hold this information.

Defining a structure

struct keyword is used to define a structure. struct define a new data type which is a collection of different type of data.

Syntax :

struct structure_name
{
 //Statements
};

Solution :-

#include <stdio.h>
struct TIME{
  int seconds;
  int minutes;
  int hours;
};

void Difference(struct TIME t1, struct TIME t2, struct TIME *diff);
int main()
{
//Ghanendra Yadav
    struct TIME t1,t2,diff;
    printf("Enter start time: \n");
    printf("Enter hours, minutes and seconds respectively: ");
    scanf("%d%d%d",&t1.hours,&t1.minutes,&t1.seconds);
    printf("Enter stop time: \n");
    printf("Enter hours, minutes and seconds respectively: ");
    scanf("%d%d%d",&t2.hours,&t2.minutes,&t2.seconds);
    Difference(t1,t2,&diff);
    printf("\nTIME DIFFERENCE: %d:%d:%d - ",t1.hours,t1.minutes,t1.seconds);
    printf("%d:%d:%d ",t2.hours,t2.minutes,t2.seconds);
    printf("= %d:%d:%d\n",diff.hours,diff.minutes,diff.seconds);
    return 0;
}

void Difference(struct TIME t1, struct TIME t2, struct TIME *differ)
{
    if(t2.seconds>t1.seconds)
{
        --t1.minutes;
        t1.seconds+=60;
    }
    differ->seconds=t1.seconds-t2.seconds;
    if(t2.minutes>t1.minutes)
{
        --t1.hours;
        t1.minutes+=60;
    }
    differ->minutes=t1.minutes-t2.minutes;
    differ->hours=t1.hours-t2.hours;
}

Output:-

C Program to Calculate Difference Between Two Time Period ( HH:MM:SS ) Using Structure

No comments:
Write comments

Recommended Posts × +