Sunday, 12 May 2013

Add time t1+t2 in c code


time AddTime(time t1, time t2)
this function takes two variables of type time and add those times and return the resultant time.
e.g if t1 = 23:45:50 and t2 = 04:20: 25 then resultant time should be 04:06:15. Note that seconds and minutes are rounded to 60 whereas hour is rounded to 24.






#include<stdio.h>
#include<stdlib.h>

struct time {
    int hour;
    int minute;
    int sec;
};
struct time t1,t2;
struct time add_time(struct time t1,struct time t2){
    struct time add;

    add.hour   = t1.hour + t2.hour;
    add.sec    = t1.sec + t2.sec;
    add.minute = t1.minute + t2.minute;
    if(add.hour>23)
    {
        add.hour=add.hour-24;
    }
     if(add.minute>59)
    {
        add.minute=add.minute-60;
    }
     if(add.sec>59)
    {
        add.sec=add.sec-60;
    }
    return add;
}
void main()
{
    struct time sum;
    printf("enter the the time 1:\n");
    printf("Enter hours, minutes and seconds respectively:\n ");
    scanf("%d%d%d",&t1.hour,&t1.minute,&t1.sec);
    printf("enter the the time 2\n\n");
    printf("Enter hours, minutes and seconds respectively:\n ");
    scanf("%d%d%d",&t2.hour,&t2.minute,&t2.sec);
    sum=add_time(t1,t2);
    printf("t1+t2  =   %d : %d : %d\n\n\n",sum.hour,sum.minute,sum.sec);
system("pause");
}


No comments:

Post a Comment