9.1. Time

As a second example of a user-defined structure, we will define a type called Time, which is used to record the time of day. The various pieces of information that form a time are the hour, minute and second, so these will be the instance variables of the structure.

The first step is to decide what type each instance variable should be. It seems clear that hour and minute should be integers. Just to keep things interesting, let’s make second a double, so we can record fractions of a second.

The active code below shows what the structure definition looks like. We can create a Time object in the usual way.

The state diagram for this object looks like this:

digraph state {
graph [compound = true,
       rankdir = "LR",
       nodesep = 0
       ranksep = 0.1]
node [fontname = "Bitstream Vera Sans",
      shape=plain]
edge [style = invis]

subgraph cluster_time {
 "hour:   " -> "          11"
 "minute:" -> "          59"
 "second:" -> "3.14159"
}
time
}

The word instance is sometimes used when we talk about objects, because every object is an instance (or example) of some type. The reason that instance variables are so-named is that every instance of a type has a copy of the instance variables for that type.

Try writing the printTime function in the commented section of the active code below. printTime should print out the time in the HOUR:MINUTE:SECONDS format. If you get stuck, you can reveal the extra problem at the end for help.

You have attempted of activities on this page