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.

Example time_AC_1
 1#include <iostream>
 2
 3struct time {
 4    int hour, minute;
 5    double second;
 6};
 7
 8int main() {
 9    time time = { 11, 59, 3.14159 };
10    std::cout << time.hour << ':' << time.minute << ':' << time.second;
11}

The state diagram in Fig. 9.1 shows this object:

time object state diagram showing hour, minute, and second fields

Fig. 9.1 Time object 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.

Q1

Click on all the statements that are variables of type price. If you make a mistake you can click on the statement again to unhighlight it.






    
    
    
}

Q2

Click on all the statements that are instance variables of type price.






    
    
    
}

Q3

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

Example time_AC_2
 1#include <iostream>
 2
 3struct time {
 4    int hour;
 5    int minute;
 6    double second;
 7};
 8
 9void print_time(time& time) {
10    // ``print_time`` should print out the time in the
11    // HOUR:MINUTE:SECONDS format. Write your implementation here.
12}
13
14int main() {
15    time time = { 11, 59, 3.14159 };
16
17    // Should output "11:59:3.14159"
18    print_time(time);
19}
Reveal Problem

Let's write the code for the print_time function. print_time should print out the time in the HOUR:MINUTE:SECONDS format.

  1.    cout << hour << ':' << minute << ':' << second;
    }
  2. cout << time.hour << ':' << time.minute << ':' << time.second;
  3. time print_time(time& time) {
  4. void print_time(time& time) {