Structure Assignment 18 — Add Two Times Using a Structure
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Add Two Times Using a Structure

📑 On this page:
  • Why 1:45 + 1:30 isn't 2:75
  • The seconds-first trick
  • The three steps
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions

Why 1:45 + 1:30 isn't 2:75

Here's what happens if you try to add times the naive way: add the hours together, add the minutes together, add the seconds together. You get 1:45 + 1:30 = 2:75. That's wrong. 75 minutes isn't a valid minute value. You have to carry one over to the hour, and the answer becomes 3:15.

That's the whole challenge of this assignment. Adding two times isn't the same as adding three pairs of numbers. You have to handle carries — when seconds go past 59, they bump the minute; when minutes go past 59, they bump the hour; when hours go past 23, they either wrap to 0 (if you're treating it as a time of day) or keep counting (if you're treating it as a duration).

The cleanest way to handle all that is to get out of hours:minutes:seconds format as soon as possible. Convert both times to total seconds. Add two integers. Then convert back. The carries happen automatically because converting back to H:M:S naturally handles the rollover — 75 minutes becomes 1 hour 15 minutes when you do the arithmetic on the total seconds. That's the trick this whole assignment is built around.

The seconds-first trick

A time like 1:45:00 is really just 1 × 3600 + 45 × 60 + 0 = 6300 seconds. And 1:30:00 is 1 × 3600 + 30 × 60 + 0 = 5400 seconds. Add the two totals: 6300 + 5400 = 11700 seconds. Now convert back: 11700 / 3600 = 3 hours (with remainder), (11700 % 3600) / 60 = 15 minutes, 11700 % 60 = 0 seconds. Answer: 3:15:00. That's exactly what you'd get by hand.

The beauty of this approach is that the carries take care of themselves. You don't need to write special code for "when minutes exceed 59, increment hours". The arithmetic of converting back from total seconds does it automatically, because total seconds is a plain number — no structure, no bounds. The structure only comes back when you split the total back into its three parts.

One thing to think about: what if the total exceeds 24 hours? If you're adding times-of-day (like 10 PM + 5 hours), the answer should probably wrap to 3 AM. If you're adding durations (like 10 hours + 5 hours), the answer is just 15 hours — no wrapping. For this assignment, we'll treat the result as a duration — the plain sum, no wrapping. That's simpler, and it matches the natural reading of "add two times". If you want time-of-day behavior, take the total modulo 86400 (the number of seconds in a day).

💡 In one line: convert each time to total seconds, add the two integers, convert the sum back to H:M:S. The carries happen automatically in the conversion.

Two time structs (1:45:00 and 1:30:00) each converted to total seconds (6300 and 5400), summed to 11700 seconds, then converted back to 3:15:00.

The three steps

Three steps, and the middle one is trivial:

  1. Convert each time to total seconds: t.hours * 3600 + t.minutes * 60 + t.seconds.
  2. Add the two second counts together.
  3. Convert the sum back to H:M:S: hours = total / 3600, minutes = (total % 3600) / 60, seconds = total % 60.

That's the whole algorithm. The carry-over is hidden inside step 3's integer division and modulo — no special cases needed. If total is 11700, then 11700 / 3600 = 3, (11700 % 3600) / 60 = 15, 11700 % 60 = 0. Done.

Time A Time B A in seconds B in seconds Sum in seconds Result
1:45:001:30:0063005400117003:15:00
0:30:450:15:20184592027650:46:05
10:00:005:30:0036000198005580015:30:00
0:0:590:0:1591600:01:00
23:59:590:0:18639918640024:00:00

The last row is interesting: 23:59:59 + 0:00:01 = 24:00:00. If you wanted time-of-day, you'd wrap to 00:00:00 by taking the total modulo 86400. As it stands, this code prints 24:00:00, which is fine as a duration.

Complete C Program

Program: add two times

#include <stdio.h>

struct time {
    int hours;
    int minutes;
    int seconds;
};

int to_seconds(struct time t) {
    return t.hours * 3600 + t.minutes * 60 + t.seconds;
}

struct time from_seconds(int total) {
    struct time t;
    t.hours   = total / 3600;
    t.minutes = (total % 3600) / 60;
    t.seconds = total % 60;
    return t;
}

int main(void) {
    struct time a = {1, 45, 0};
    struct time b = {1, 30, 0};

    int total = to_seconds(a) + to_seconds(b);
    struct time result = from_seconds(total);

    printf("Time A : %02d:%02d:%02d\n", a.hours, a.minutes, a.seconds);
    printf("Time B : %02d:%02d:%02d\n", b.hours, b.minutes, b.seconds);
    printf("Sum    : %02d:%02d:%02d\n",
           result.hours, result.minutes, result.seconds);

    return 0;
}
                                    

And here's a version that reads both times from the user, so you can try any pair:

Variant: read both times from the user

#include <stdio.h>

struct time {
    int hours;
    int minutes;
    int seconds;
};

int to_seconds(struct time t) {
    return t.hours * 3600 + t.minutes * 60 + t.seconds;
}

struct time from_seconds(int total) {
    struct time t;
    t.hours   = total / 3600;
    t.minutes = (total % 3600) / 60;
    t.seconds = total % 60;
    return t;
}

int main(void) {
    struct time a, b;

    printf("Time A (hh mm ss): ");
    scanf("%d %d %d", &a.hours, &a.minutes, &a.seconds);
    printf("Time B (hh mm ss): ");
    scanf("%d %d %d", &b.hours, &b.minutes, &b.seconds);

    int total = to_seconds(a) + to_seconds(b);
    struct time result = from_seconds(total);

    printf("\n%02d:%02d:%02d + %02d:%02d:%02d = %02d:%02d:%02d\n",
           a.hours, a.minutes, a.seconds,
           b.hours, b.minutes, b.seconds,
           result.hours, result.minutes, result.seconds);

    return 0;
}
                                    

Both versions use the same two helper functions — to_seconds and from_seconds. Those are the only things that need to change if you want to add three times or ten times; the main function just calls them in a loop.

Program Output

Time A : 01:45:00
Time B : 01:30:00
Sum    : 03:15:00
                                

And for the user-input version, try one that forces a carry through seconds into minutes:

Time A (hh mm ss): 0 30 45
Time B (hh mm ss): 0 15 20

00:30:45 + 00:15:20 = 00:46:05
                                

Notice how 45 + 20 = 65 seconds becomes 1 minute 5 seconds, and that 1 minute carries up to the minute count. The code doesn't do anything special for this — it just works, because 65 seconds is total_seconds = 1845 + 920 = 2765, and 2765 / 60 = 46 (minutes), 2765 % 60 = 5 (seconds). The carry is automatic. Try a case that rolls all the way over to the hour — say 0:59:30 + 0:0:45 should give 1:00:15.

Step-by-Step Explanation

Walk-through with the main version (1:45:00 + 1:30:00 = 3:15:00).

1. The struct

Same struct time as the last two assignments. Three ints — hours, minutes, seconds. Nothing new here. This is the third time we've used this struct in a row, so it should feel familiar by now.

2. The to_seconds helper

to_seconds(t) returns t.hours * 3600 + t.minutes * 60 + t.seconds. For 1:45:00 that's 1 * 3600 + 45 * 60 + 0 = 3600 + 2700 = 6300. For 1:30:00 that's 3600 + 1800 = 5400. The math is straightforward — it's just counting how many seconds make up each part and adding them up.

3. The sum

to_seconds(a) + to_seconds(b) = 6300 + 5400 = 11700. Nothing tricky here — it's just integer addition. The key insight is that once you're in the "total seconds" representation, adding times is the same as adding plain integers. No structure, no carries, no special cases.

4. The from_seconds helper

from_seconds(total) reverses the conversion. total / 3600 is how many whole hours fit in the total — 11700 / 3600 = 3, so 3 hours. The remainder is 11700 % 3600 = 900 seconds, which is 900 / 60 = 15 minutes. The final remainder 11700 % 60 = 0 is the seconds. Result: 3:15:00.

5. Why the carry works automatically

There's no explicit "if minutes > 59, then hours++" anywhere in the code. The carry happens because the conversion math is correct. If minutes go past 59, they contribute to the "seconds" total, which when divided by 3600 gives the extra hour. In the 1:45 + 1:30 example, the extra 75 minutes contribute 75 * 60 = 4500 extra seconds to the total, which becomes 1 extra hour and 15 extra minutes when converted back. The arithmetic handles the rollover, not the programmer.

6. What about negative or out-of-range inputs?

The code assumes the inputs are valid times — hours 0-23, minutes and seconds 0-59. If you pass in t.minutes = 99, the to_seconds function treats it as 99 minutes worth of seconds, which is 1 hour 39 minutes in disguise. The sum will be technically correct — just not what you probably meant. A real program would validate before converting. For this assignment, assuming valid input is fine.

7. Why helpers, not inline code

You could write the conversion inline in main: int total = (a.hours * 3600 + a.minutes * 60 + a.seconds) + (b.hours * 3600 + b.minutes * 60 + b.seconds);. That works but it's a wall of arithmetic. The helpers make the logic cleaner and let you reuse it — if you later want to add three times, you just call to_seconds three times and sum. Functions are how you keep that kind of growth manageable.

🎯 Remember this: convert to seconds, add, convert back. The carries happen automatically in the back-conversion. No special "if minutes > 59" code needed. Use helper functions to keep the main logic clean.

Frequently Asked Questions

1. Why not add hours, minutes, seconds separately and then fix the carries?

You could — compute s = a.seconds + b.seconds, m = a.minutes + b.minutes + s / 60, h = a.hours + b.hours + m / 60, then normalise m = m % 60, s = s % 60. It works and it's arguably more direct. But the seconds-first approach is cleaner because it uses one piece of arithmetic (convert back from seconds) for all the carries. Both are valid; pick whichever you find easier to reason about.

2. What if the total goes past 24 hours?

Two choices. If you're adding durations (10 hours + 5 hours = 15 hours), don't wrap — the answer is just 15:00:00. If you're adding times of day (10 PM + 5 hours = 3 AM), wrap by taking total % 86400 before converting back. 86400 is 24 * 3600, the number of seconds in a day. For this assignment, the code treats the result as a duration, so it prints 25:30:00 if you feed in 20:00:00 + 5:30:00. That's fine as a duration.

3. What if the user enters negative seconds?

The current code would produce nonsense, because division and modulo on negative integers don't work the way most people expect. For example, -5 / 60 is 0 (not -1) in C, and -5 % 60 is -5 (not 55). A real program would validate or take absolute values. For this assignment, assuming positive inputs is fine.

4. Can I add more than two times?

Yes — sum the total seconds for each time, then convert once at the end. Something like int total = to_seconds(a) + to_seconds(b) + to_seconds(c);, then from_seconds(total). Or with an array of times, loop over them accumulating seconds, then convert. The same trick scales to any number of times.

5. Why does from_seconds use % instead of subtraction?

Because % is the natural way to get the remainder after a division. total % 3600 gives the leftover seconds after removing whole hours, and (total % 3600) / 60 gives the whole minutes within that leftover. It's the same as subtracting hours * 3600 and then dividing by 60, just more compact. Both are correct; the modulo version is the standard idiom.

6. How would I compute the difference between two times?

Same trick: total = abs(to_seconds(a) - to_seconds(b)), then from_seconds(total). The absolute value handles the case where b comes before a. It's the exact reverse of addition, and the helper functions are already in place. That would be a good exercise after this assignment — swap the plus for a minus and add an abs.

💡 Tip: After this, try adding the same time to itself three times (a + a + a) and see if it gives the same result as multiplying the seconds by 3. Then try computing the difference between two times and printing the result as hours:minutes:seconds. Both exercises use the same helpers, so the code is short — just the main function changes.

📖 Related Tutorials

  • 16. Create a Structure to Represent a Time
  • 17. Initialize and Display the Time Using a Structure
  • 19. Create a Structure to Represent an Employee
  • Structures and Functions
  • Accessing Structure Members
  • Defining a Structure
  • Array of Structures
  • All 25 Structure Assignments

Previous Topic: -->> 17. Initialize and Display the Time Using a Structure   ||   Next Topic: -->> 19. Create a Structure to Represent an Employee


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.