Concept explainers
Add the following member function to the ADT class DigitalTime defined in Displays 12.1 and 12.2:
void DigitalTime::intervalSince(const DigitalTime& aPreviousTime,
int& hoursInInterval, int& minutesInInterval) const
This function computes the time interval between two values of type DigitalTime. One of the values of type DigitalTime is the object that calls the member function intervalSince, and the other value of type DigitalTime is given as the first argument. For example, consider the following code:
DigitalTime current(5, 45), previous(2, 30);
int hours, minutes;
current.intervalSince(previous, hours, minutes);
cout << “The time interval between ” << previous
<< “ and ” << current << endl
<< “is ” « hours « “ hours and ”
<< minutes << “ minutes.\n”;
In a
The time interval between 2:30 and 5:45
is 3 hours and 15 minutes.
Allow the time given by the first argument to be later in the day than the time of the calling object. In this case, the time given as the first argument is assumed to be on the previous day. You should also write a program to test this revised ADT class.
Compute interval between two times
Program Plan:
- The interface file “dtime.h” is same as in the Display 12.1 however user needs to add the member function “void intervalSince(const DigitalTime& aPreviousTime, int& hoursInInterval, int& minutesInInterval)const;”.
- In the implementation file “dtime.cpp”, add the function definition for function “intervalSince”.
- In this function, first initializes the variables “hoursInInterval” and “minutesInInterval” to “0”.
- Declare a variable for compute the difference in “DigitalTime”.
- Compute the hour difference using “hour - aPreviousTime.hour”.
- Compute the minute difference using “minute - aPreviousTime.minute”.
- Check the condition of “hour” and “minutes”.
- Finally store the hours and minutes difference in their respective variables.
- In the application file that is “main.cpp”.
- Include the directive “dtime.h”.
- Define main function.
- Initializes the time for current and previous.
- Declare “int” variables for “hours” and “minutes”.
- Call “intervalSince()” function.
- Display the interval between two times.
The below C++ program is used to compute interval between two values of type “DigitalTime”.
Explanation of Solution
Program:
Modified code for “dtime.h”:
//DISPLAY 12.1 Interface File for DigitalTime
//Header file dtime.h: This is the INTERFACE for the class DigitalTime.
//Values of this type are times of day. The values are input and output in
//24-hour notation, as in 9:30 for 9:30 AM and 14:45 for 2:45 PM.
#include <iostream>
using namespace std;
class DigitalTime
{
public:
friend bool operator ==(const DigitalTime& time1, const DigitalTime& time2);
//Returns true if time1 and time2 represent the same time;
//otherwise, returns false.
DigitalTime(int theHour, int theMinute);
//Precondition: 0 <= theHour <= 23 and 0 <= theMinute <= 59.
//Initializes the time value to theHour and theMinute.
DigitalTime( );
//Initializes the time value to 0:00 (which is midnight).
void advance(int minutesAdded);
//Precondition: The object has a time value.
//Postcondition: The time has been changed to minutesAdded minutes later.
void advance(int hoursAdded, int minutesAdded);
//Precondition: The object has a time value.
//Postcondition: The time value has been advanced
//hoursAdded hours plus minutesAdded minutes.
void intervalSince(const DigitalTime& aPreviousTime, int& hoursInInterval, int& minutesInInterval)const;
//Precondition: The object has a time value.
//Precondition: The aPreviousTime object has a time value
//Postcondition: The hoursInInterval represents the number of hours that have passed and the minutesInInterval represents the number of minutes that have passed
friend istream& operator >>(istream& ins, DigitalTime& theObject);
//Overloads the >> operator for input values of type DigitalTime.
//Precondition: If ins is a file input stream, then ins has already been
//connected to a file.
friend ostream& operator <<(ostream& outs, const DigitalTime& theObject);
//Overloads the << operator for output values of type DigitalTime.
//Precondition: If outs is a file output stream, then outs has already been
//connected to a file.
private:
int hour;
int minute;
};
Modified code for “dtime.cpp”:
//DISPLAY 12.2 Implementation File for DigitalTime
//Implementation file dtime.cpp (Your system may require some
//suffix other than .cpp): This is the IMPLEMENTATION of the ADT DigitalTime.
//The interface for the class DigitalTime is in the header file dtime.h.
#include <iostream>
#include <cctype>
#include <cstdlib>
#include "dtime.h"
using namespace std;
//These FUNCTION DECLARATIONS are for use in the definition of
//the overloaded input operator >>:
void readHour(istream& ins, int& theHour);
//Precondition: Next input in the stream ins is a time in 24-hour notation,
//like 9:45 or 14:45.
//Postcondition: theHour has been set to the hour part of the time.
//The colon has been discarded and the next input to be read is the minute.
void readMinute(istream& ins, int& theMinute);
//Reads the minute from the stream ins after readHour has read the hour.
int digitToInt(char c);
//Precondition: c is one of the digits '0' through '9'.
//Returns the integer for the digit; for example, digitToInt('3') returns 3.
bool operator ==(const DigitalTime& time1, const DigitalTime& time2)
{
return (time1.hour == time2.hour && time1.minute == time2.minute);
}
//Uses iostream and cstdlib:
DigitalTime::DigitalTime(int theHour, int theMinute)
{
if (theHour < 0 || theHour > 23 || theMinute < 0 || theMinute > 59)
{
cout << "Illegal argument to DigitalTime constructor.";
exit(1);
}
else
{
hour = theHour;
minute = theMinute;
}
}
DigitalTime::DigitalTime( ) : hour(0), minute(0)
{
//Body intentionally empty.
}
void DigitalTime::advance(int minutesAdded)
{
int grossMinutes = minute + minutesAdded;
minute = grossMinutes%60;
int hourAdjustment = grossMinutes/60;
hour = (hour + hourAdjustment)%24;
}
void DigitalTime::advance(int hoursAdded, int minutesAdded)
{
hour = (hour + hoursAdded)%24;
advance(minutesAdded);
}
//Uses iostream:
ostream& operator <<(ostream& outs, const DigitalTime& theObject)
{
outs << theObject.hour << ':';
if (theObject.minute < 10)
outs << '0';
outs << theObject.minute;
return outs;
}
//Uses iostream:
istream& operator >>(istream& ins, DigitalTime& theObject)
{
readHour(ins, theObject.hour);
readMinute(ins, theObject.minute);
return ins;
}
int digitToInt(char c)
{
return ( static_cast<int>(c) - static_cast<int>('0') );
}
//Uses iostream, cctype, and cstdlib:
void readMinute(istream& ins, int& theMinute)
{
char c1, c2;
ins >> c1 >> c2;
if (!(isdigit(c1) && isdigit(c2)))
{
cout << "Error illegal input to readMinute\n";
exit(1);
}
theMinute = digitToInt(c1)*10 + digitToInt(c2);
if (theMinute < 0 || theMinute > 59)
{
cout << "Error illegal input to readMinute\n";
exit(1);
}
}
//Uses iostream, cctype, and cstdlib:
void readHour(istream& ins, int& theHour)
{
char c1, c2;
ins >> c1 >> c2;
if ( !( isdigit(c1) && (isdigit(c2) || c2 == ':' ) ) )
{
cout << "Error illegal input to readHour\n";
exit(1);
}
if (isdigit(c1) && c2 == ':')
{
theHour = digitToInt(c1);
}
else //(isdigit(c1) && isdigit(c2))
{
theHour = digitToInt(c1)*10 + digitToInt(c2);
ins >> c2;//discard ':'
if (c2 != ':')
{
cout << "Error illegal input to readHour\n";
exit(1);
}
}
if ( theHour < 0 || theHour > 23 )
{
cout << "Error illegal input to readHour\n";
exit(1);
}
}
/*Function definition compute interval between the two values of type DigitalTime */
void DigitalTime::intervalSince(const DigitalTime& aPreviousTime, int& hoursInInterval, int& minutesInInterval) const
{
/* Initializes the value of hours in interval to "0" */
hoursInInterval = 0;
/* Initializes the value of minutes in interval to "0" */
minutesInInterval = 0;
/* Declare the variable for time difference */
DigitalTime diff;
/* Compute hour difference */
diff.hour = hour - aPreviousTime.hour;
/* Compute minutes difference */
diff.minute = minute - aPreviousTime.minute;
/* Check condition */
if (hour < aPreviousTime.hour || hour == aPreviousTime.hour && minute < aPreviousTime.minute)
{
//Display given message
cout << "Preceding time is in the preceding day" << endl;
diff.hour = 24 + (hour - aPreviousTime.hour);
}
/* Check the condition hour */
if (diff.minute < 0)
{
diff.hour--;
diff.minute = diff.minute + 60;
}
/* Store hours and minutes interval in respective variable */
hoursInInterval = diff.hour;
minutesInInterval = diff.minute;
return;
}
Modified “main.cpp”:
//Header file
#include <iostream>
//Header file for "dtime.h"
#include "dtime.h"
//For standard input and output
using namespace std;
//Main function
int main( )
{
//Declare time
DigitalTime current(5, 45), previous(2, 30);
//Declare "int" variables
int hours, minutes;
/* Call intervalSince() function */
current.intervalSince(previous, hours, minutes);
/* Display given time interval */
cout << "The time interval between " << previous << " and " << current << endl << "is " << hours << " hours and " << minutes << " minutes.\n";
return 0;
}
The time interval between 2:30 and 5:45
is 3 hours and 15 minutes.
Want to see more full solutions like this?
Chapter 12 Solutions
Problem Solving with C++ (10th Edition)
Additional Engineering Textbook Solutions
Web Development and Design Foundations with HTML5 (9th Edition) (What's New in Computer Science)
Starting Out With Visual Basic (8th Edition)
Starting Out with Programming Logic and Design (4th Edition)
Absolute Java (6th Edition)
Java: An Introduction to Problem Solving and Programming (8th Edition)
- array of Payroll ObjectsDesign a PayRoll class that has data members for an employee’shourly pay rate and number of hours worked. Write a program withan array of seven PayRoll objects. The program should read thenumber of hours each employee worked and their hourly pay ratefrom a file and call class functions to store this information in theappropriate objects. It should then call a class function, once foreach object, to return the employee’s gross pay, so this informationcan be displayed.arrow_forwardPS: see image for question.arrow_forwardc++ please The Critter class is a base class with some basic functionality for running simulations of different kinds of critters. Critters can move, act, and remember their history. A typical simulation contains a number of critters of different types. In each step of the simulation, the act member function will be called on each critter. Define a class Sloth derived from Critter that simulates a sloth. Sloths alternate between eating and sleeping. Add the word "eat" or "sleep" to the history each time the act function is called. The implementation of the Critter class is not shown. Complete the following file: sloth_Tester.cpp #include <iostream>using namespace std; #include "critter.h" /**A sloth eats and sleeps.*/class Sloth : public Critter{public:Sloth();. . .private:. . .}; Sloth::Sloth(){. . .} void Sloth::act(){if (...){add_history("eat");...}else{add_history("sleep");...}} int main(){Sloth sloth;sloth.act();cout << sloth.get_history() << endl;cout <<…arrow_forward
- 1- A complex number has the form a+bi , can be expressed as theordered pair of real numbers (a,b). The class represents the real andimaginary parts as double precision values.Provide a constructor that enables an object of this class to beinitialized when it is instantiated. The constructor should containdefault values.Provide Public member functions for each of the followingarithmetic’s functions (addition – subtraction – multiplication –division), a complex absolute value operation, printing the number inthe form (a,b), printing the real part , printing the imaginary part andfinal overload the == operator to allow comparisons of two complexnumbers.Include any additional operations that you think would be useful fora complex number class.Design, implement, and test your class.arrow_forwardDefine a class called token number that incorporates a tokens number (could be the last 3 digits of your arid number) and its location. Number each token object as it is created. Use two variables of the angle class to represent the tokens latitude and longitude. A member function of the token class should get a position from the user and store it in the object; another should report the serial number and position. Design a main() program that creates three token, asks the user to input the position of each, and then displays each tokens numberarrow_forwardImplement a class named Animal has two private member variables: name of type string and numLegs of type int, and has the following member functions: • setName—Function to set the name • setNumLegs—Function to set the number of animal legs • getName—Value-returning function to return the name • getNumLegs—Value-returning function to return the number of animal legs • speak()—Value-returning function to return the empty string • move()—Value-returning function to return the empty string • print()—Outputs the data stored in the instance variables with the appropriate titles • Constructor with parameter—Sets the values of the instance variables to the values specified by the user, in default: sets name to the empty string and number of legs to 0 2. Using an Animal class as a base class, implement two derived classes simulating a Cat and Dog, each redefining three functions constructor, speak(), move() to represent each animal the most suitable. 3. Write a function to handle the…arrow_forward
- objective of the project: Implement a class address. An address has a house number street optional apartment number city state postal code. All member variables should be private and the member functions should be public. Implement two constructors: one with an apartment number one without an appartment number. Implement a print function that prints the address with the street on one line and the city, state, and postal code on the next line. Implement a member function comesBefore that tests whether one address comes before another when the addresses are compared by postal code. Returns false if both zipcodes are equal. Use the provided main.cpp to start with. The code creates three instances of the Address class (three objects) to test your class. Each object will utilize a different constructor. You will need to add the class definition and implementation. The comesBefore function assumes one address comes before another based on zip code alone. The test will also return…arrow_forwardProgramming Exercise 11-2 dateType.h file provided #ifndef date_H #define date_H class dateType { public: void setDate(int month, int day, int year); //Function to set the date. //The member variables dMonth, dDay, and dYear are set //according to the parameters //Postcondition: dMonth = month; dDay = day; // dYear = year int getDay() const; //Function to return the day. //Postcondition: The value of dDay is returned. int getMonth() const; //Function to return the month. //Postcondition: The value of dMonth is returned. int getYear() const; //Function to return the year. //Postcondition: The value of dYear is returned. void printDate() const; //Function to output the date in the form mm-dd-yyyy. bool isLeapYear(); //Function to determine whether the year is a leap year. dateType(int month = 1, int day = 1, int year = 1900); //Constructor to…arrow_forwardclockType.h file provided //clockType.h, the specification file for the class clockType#ifndef H_ClockType#define H_ClockType class clockType {public: void setTime(int hours, int minutes, int seconds); //Function to set the time. //The time is set according to the parameters. //Postcondition: hr = hours; min = minutes; // sec = seconds // The function checks whether the values of // hours, minutes, and seconds are valid. If a // value is invalid, the default value 0 is // assigned. void getTime(int& hours, int& minutes, int& seconds) const; //Function to return the time. //Postcondition: hours = hr; minutes = min; // seconds = sec void printTime() const; //Function to print the time. //Postcondition: The time is printed in the form // hh:mm:ss. void incrementSeconds(); //Function to increment the time by one…arrow_forward
- in c++ write aprogram to Create a class Rectangle with length and breadth as private data members and also provide the following member functions: getdata(): gets the length and breadth of rectangle. calarea(): return the area of the rectangle. calperi(): return the perimeter of the rectangle. issquare(): return true if the rectangle is squarearrow_forwardDefine a class called ‘token number’ that incorporates a token’s number and its location. Number each token object as it is created. Use two variables of the angle class to represent the token’s latitude and longitude. A member function of the token class should get a position from the user and store it in the object; another should report the serial number and position. Design a main() program that creates three token, asks the user to input the position of each, and then displays each token’s number and position.arrow_forwardC++arrow_forward
- C++ for Engineers and ScientistsComputer ScienceISBN:9781133187844Author:Bronson, Gary J.Publisher:Course Technology PtrC++ Programming: From Problem Analysis to Program...Computer ScienceISBN:9781337102087Author:D. S. MalikPublisher:Cengage LearningMicrosoft Visual C#Computer ScienceISBN:9781337102100Author:Joyce, Farrell.Publisher:Cengage Learning,