Skip to main content

How To Think Like a Computer Scientist C++ Edition The Pretext Interactive Version

Section 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.
Listing 9.1.1. This active code 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:
described in detail following the image
The word time is written above a box. Inside the box, hour has the value 11, minute has the value 59, and second has the value 3.14159.
Figure 9.1.2. State diagram
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.

Checkpoint 9.1.1.

Which of the following words are variables of type Price?
struct Price {
  int dollar, cents;
};

int main() {
  Price sandwich = { 3, 45 };
  Price coffee = { 2, 50 };
  Price pastry = { 2, 0 };
}
  • sandwich, coffee, pastry
  • Correct!
  • dollar, cents
  • Try again. We are looking for variable names not instances of a structure.
  • Price, struct
  • Try again. ``struct`` and ``Price`` are not variables.

Checkpoint 9.1.2.

Which of the following words are instance variables of the Price structure?
struct Price {
  int dollar, cents;
};

int main() {
  Price sandwich = { 3, 45 };
  Price coffee = { 2, 50 };
  Price pastry = { 2, 0 };
}
  • sandwich, coffee, pastry
  • These are variables of type Price.
  • dollar, cents
  • Correct!
  • Price, struct
  • Try again. ``struct`` and ``Price`` are not variables.

Checkpoint 9.1.3.

Which of the following words are a user-defined structure?
struct Price {
  int dollar, cents;
};

int main() {
  Price sandwich = { 3, 45 };
  Price coffee = { 2, 50 };
  Price pastry = { 2, 0 };
}
  • sandwich, coffee, pastry
  • These are variables of type Price.
  • dollar, cents
  • These are instance variables of the Price structure.
  • Price
  • Correct!

Checkpoint 9.1.4.

Try writing the printTime function in the commented section of this active code. 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.

Exercises Exercises

yes.

Let’s write the code for the printTime function. printTime should print out the time in the HOUR:MINUTE:SECONDS format.
You have attempted 1 of 5 activities on this page.