Structure Assignment 16 — Create a Structure to Represent a Time
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Create a Structure to Represent a Time (Hours, Minutes, Seconds)

📑 On this page:
  • Three numbers that make a time
  • The struct and its fields
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to model a time with three ints — hours, minutes, seconds
  • How to fill the struct at declaration, or set the fields one at a time
  • How to print a time in HH:MM:SS format using %02d
  • Why the padding matters — 9:5:3 should show as 09:05:03
  • Why a time struct is the starting point for add, difference, and comparison programs

Three numbers that make a time

A time of day has three parts — hours, minutes, and seconds. You could keep them in three separate variables, but then every function that deals with times would need three parameters, and any operation that produces a time would need to return three values. That's clumsy. A struct wraps them into one value: struct time t; is a single variable holding all three parts of one time.

All three fields are integers. Hours go from 0 to 23 (in 24-hour format) or 0 to 12 (12-hour format with AM/PM). Minutes and seconds go from 0 to 59. There's no such thing as "12.5 hours" or "30.7 minutes" in normal use, so int is the natural type. Some programs use long for seconds-since-midnight, but that's a different representation — for a time as three separate fields, int is right.

The printing is where this assignment gets its little detail. If you print "9:5:3", it looks wrong. It should be "09:05:03". The %02d format specifier pads single digits with a leading zero, so each part always has two digits. It's the same trick we used for dates, and it's the difference between "a program that prints numbers" and "a program that prints a time".

💡 In one line: struct time { int hours; int minutes; int seconds; }; is the type. struct time t = {14, 30, 45}; is one time. Print with %02d:%02d:%02d for the HH:MM:SS look.

A time struct drawn as three boxes stacked vertically: hours 14, minutes 30, seconds 45. A clock icon next to it shows the same time as 14:30:45.

The struct and its fields

Three ints, one for each part:

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

Same as every other struct — don't forget the semicolon after the closing brace. The order matters for the initializer list (hours first, minutes, then seconds), but not for anything else.

Member Type Meaning Valid range
hoursintHours since midnight0 to 23 (24-hour) or 0 to 12 (12-hour)
minutesintMinutes past the hour0 to 59
secondsintSeconds past the minute0 to 59

There's no rule in C that enforces the ranges. You could set t.minutes = 75 and the struct would happily accept it. It's up to the program to keep the values in the right range, or to normalise them (e.g., 75 minutes = 1 hour 15 minutes). We'll come back to that in the FAQ.

Complete C Program

Program: define a time and print it

#include <stdio.h>

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

int main(void) {
    struct time t = {14, 30, 45};

    printf("Time : %02d:%02d:%02d\n", t.hours, t.minutes, t.seconds);
    return 0;
}
                                    

And here's a version that reads the time from the user, which is closer to what you'd write in a real program:

Variant: read the time from the user

#include <stdio.h>

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

int main(void) {
    struct time t;

    printf("Enter time (hh mm ss): ");
    scanf("%d %d %d", &t.hours, &t.minutes, &t.seconds);

    printf("Time : %02d:%02d:%02d\n", t.hours, t.minutes, t.seconds);
    return 0;
}
                                    

The first version hardcodes the time so you can see the struct filled and printed. The second reads it from the user so you can try other times. Same struct, same fields, same printf — only the fill method is different.

Program Output

Time : 14:30:45
                                

And for the user-input version, try a time with single-digit parts:

Enter time (hh mm ss): 9 5 3
Time : 09:05:03
                                

Notice that 9 5 3 prints as 09:05:03 — the %02d adds the leading zeros. Without it, you'd see 9:5:3, which is technically correct but doesn't look like a time. Try midnight (0 0 0), which should print as 00:00:00, and noon (12 0 0), which should print as 12:00:00.

Step-by-Step Explanation

Short program, quick walk-through.

1. The struct definition

struct time { int hours; int minutes; int seconds; }; — three ints, one for each part of the time. The names are for humans reading the code; C doesn't care what you call them as long as you use them consistently.

2. Declaring and filling

struct time t = {14, 30, 45}; creates a time with hours 14, minutes 30, seconds 45. That's 2:30:45 PM in 24-hour notation. The values go into the fields in the order they're declared — hours first, minutes, then seconds. If you swapped the field order in the struct, you'd have to swap the values here too (or use named fields: {.seconds = 45, .minutes = 30, .hours = 14}).

3. Printing the time

printf("%02d:%02d:%02d\n", t.hours, t.minutes, t.seconds); — three values, three format specifiers. The %02d means "print an integer, at least two digits, pad with a leading zero if needed". So 9 becomes 09, 30 stays 30. The colons between them are literal characters. The result reads like a standard time.

4. Why %02d for all three fields?

Because times are conventionally written with two digits for each part. 09:05:03 reads more clearly than 9:5:3 — it's the format people are used to seeing on clocks, watches, and timers. Even 00:00:00 needs the zeros; without them, you'd just see "0:0:0" and have to guess which field is which.

5. Reading from the user

The scanf variant uses scanf("%d %d %d", &t.hours, &t.minutes, &t.seconds). The user types three numbers separated by spaces (or any whitespace), and scanf fills the three fields. The & is essential — each field needs its address passed so scanf knows where to write.

6. What about 12-hour format?

If you want to print in 12-hour format with AM/PM, you'd store the time in 24-hour form and convert at print time. If t.hours > 12, subtract 12 and use "PM". If t.hours == 0, use 12 and "AM". If t.hours == 12, use 12 and "PM". Otherwise use the hours as-is with "AM". It's a small if-else, but it's a useful exercise because it shows that the storage format doesn't have to match the display format.

7. Where this leads

Adding two times is the next assignment: the natural approach is to convert each time to seconds-since-midnight, add, then convert back. That's the same "convert to a single number" idea we used for dates. Computing the difference between two times is the same idea in reverse — convert both to seconds, subtract, take the absolute value. So this small struct is the foundation for the next two assignments.

🎯 Remember this: a time is three ints — hours, minutes, seconds. Fill it with {14, 30, 45} or read from the user with scanf. Print with %02d:%02d:%02d for the HH:MM:SS format. %02d pads single digits with a leading zero, which makes times look right.

Frequently Asked Questions

1. Why are the fields ints and not strings?

Because time arithmetic — adding, subtracting, comparing — needs numeric values. An hour is a number, a minute is a number, a second is a number. Storing them as ints lets you add and subtract directly. If you stored "14:30:45" as a string, you'd have to parse it back into numbers every time you wanted to do anything with it, which is slower and more error-prone.

2. Should the hours be 0-23 or 0-12?

Both work, but 0-23 (24-hour format) is simpler for arithmetic. Storing hours as 0-23 means the time-of-day is a unique number: 14 means 2 PM, and you don't need to track whether it's AM or PM. If you want to display in 12-hour format, convert at print time. Storing in 24-hour and displaying in 12-hour is the usual approach.

3. What if I enter 25 for hours?

The struct will accept it, but 25 hours doesn't make sense. A real program would either reject the input (if (t.hours < 0 || t.hours > 23) { error }) or normalise it (25 hours = 1 hour next day). Same for minutes and seconds ≥ 60. For this assignment, assuming valid input is fine, but the validation habit is worth adding once you're comfortable with the basics.

4. How would I convert this to seconds since midnight?

Multiply and add: int total = t.hours * 3600 + t.minutes * 60 + t.seconds;. That gives a single number representing the time of day, from 0 (midnight) to 86399 (just before midnight). This is useful for comparisons, differences, and adding times — all of which become simple integer arithmetic on the total. This is the trick for the next assignment (adding two times).

5. Can I compare two times with ==?

Not directly — C doesn't provide structure comparison with ==. You'd compare field by field: if (a.hours == b.hours && a.minutes == b.minutes && a.seconds == b.seconds). Or convert both to seconds-since-midnight and compare the integers: if (to_seconds(a) == to_seconds(b)). The second approach is shorter and works for < and > as well.

6. What's the difference between this struct and time.h's struct tm?

time.h has struct tm with many more fields — seconds, minutes, hours, day, month, year, weekday, day-of-year, daylight-saving flag. It's designed to represent a complete timestamp, not just a time of day. Our struct is much simpler, enough for basic time-of-day storage. In real code, you'd often use time.h. For learning how structs work, ours is the right size.

💡 Tip: After this, try adding a small check that prints "AM" or "PM" depending on the hours. If t.hours < 12, it's AM; otherwise PM. And try converting to 12-hour format: if (t.hours == 0) hours = 12;, else if (t.hours > 12) hours = t.hours - 12;. It's a small if-else that makes the output feel more human.

📖 Related Tutorials

  • 17. Initialize and Display the Time Using a Structure
  • 18. Add Two Times Using a Structure
  • 15. Find the Difference Between Two Dates Using a Structure
  • Defining a Structure
  • Accessing Structure Members
  • Structure Initialization
  • Array of Structures
  • All 25 Structure Assignments

Previous Topic: -->> 15. Find the Difference Between Two Dates Using a Structure   ||   Next Topic: -->> 17. Initialize and Display the Time Using a Structure


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.