LearnFrenzy
Sign in Take a free test

Structures, Unions, Enums · Structure Programs · Question 3

Add two times (hh:mm:ss) using structures in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Add two durations stored as hours, minutes and seconds, carrying over correctly.

Solution
main.c
#include <stdio.h>

struct duration {
    int h, m, s;
};

struct duration add(struct duration a, struct duration b) {
    int total = (a.h + b.h) * 3600 + (a.m + b.m) * 60 + (a.s + b.s);   /* work in seconds */
    return (struct duration){total / 3600, total % 3600 / 60, total % 60};
}

int main(void) {
    struct duration t = add((struct duration){1, 45, 50}, (struct duration){2, 20, 25});
    printf("%02d:%02d:%02d\n", t.h, t.m, t.s);
    return 0;
}

Output Verified by compiling and running

04:06:15

Converting to seconds and back makes the carrying automatic: 6350 + 8425 = 14775 s = 4 h 6 min 15 s. Compound literals pass the two times without named variables.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links