Problem Solving with C++, Student Value Edition
Problem Solving with C++, Student Value Edition
10th Edition
ISBN: 9780134543680
Author: Walter Savitch
Publisher: PEARSON
bartleby

Concept explainers

bartleby

Videos

Textbook Question
Chapter 12, Problem 1P

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 program that uses your revised version of the DigitalTime ADT, this code should produce the following output:

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.

Expert Solution & Answer
Check Mark
Program Plan Intro

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.
Program Description Answer

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;

}

Sample Output

The time interval between 2:30 and 5:45

is 3 hours and 15 minutes.

Want to see more full solutions like this?

Subscribe now to access step-by-step solutions to millions of textbook problems written by subject matter experts!
Students have asked these similar questions
c++ Write a class called Triangle with three private integer data members a, b, and c as the lengths of its three edges. This class should have the following functions:  a constructor with three parameters representing the three edges a function isTriangle() which returns true if the three edges are all positive and they satisfy the triangle inequality where a+b> c, a+c> b, b+c> a, otherwise returns false. a function getPerimeter() which returns the perimeter of the triangle. (where, the perimeter = a+b+c)Then, test the above class in a program.
Consider a class named Calculator with typical four specific functionalities i.e. addition, subtraction, multiplication, and division. Implement these functionalities as four functions with two parameters. It is also required to overload all these functions for int and double data types. In the main function, create an object of class Calculator and invoke its member functions while passing parameters of int and double type.
Q1) Write the Code the following scenario. Write an abstract function named receivePay in interface with return type double and no parameters. Write another incomplete function, name Show with return type void and an argument of type int in that interface. Build a class with name Bill that implements the above interface. Bill class with name BillId , itemsquantity and itemsprice with proper datatypes with private access . Define two constructors,one default and other is parameterized to initialize the class members . Now receivePay has to beimplemented in such a way that its displays product of itemsquantity and itemsprice and Display function will display the BillId.Can we do same task with abstract class instead of interface? NOTE:SUBJECT:CSHARP (VISUAL PROGRAMMING)

Additional Engineering Textbook Solutions

Find more solutions based on key concepts
When displaying a Java applet, the browser invokes the _____ to interpret the bytecode into the appropriate mac...

Web Development and Design Foundations with HTML5 (9th Edition) (What's New in Computer Science)

What is an object?

Starting Out With Visual Basic (8th Edition)

What is a program?

Starting Out with Programming Logic and Design (4th Edition)

Knowledge Booster
Computer Science
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.
Similar questions
  • write a class Point with parametrized constructor. This class have four member variables, a,b,c,d. Write the following member functions a. drawTriangle(int x, int y, int z ) b. drawRectangle(int x, int y, int z, int a). Each function should display the length of lines for each of the shape (triangle, rectangle). For example triangle should calculate length of its three lines by following methods as shown in code. Note: the number of lines depends on the name of shape. void drawTriangle(int x, int y, int z ) { int line 1 = x - y; // convert to positive value if line length is negative int line 2 = y -z; int line 3 = z -x; cout<< The length of each lines is: << //// here display length of each line with proper formatting. } Write similar code for drawRectangle(int x, int y, int z, int a). Wtite main function to call these three function
    The base class Pet has protected data members petName, and petAge. The derived class Dog extends the Pet class and includes a private data member for dogBreed. Complete main() to: create a generic pet and print information using PrintInfo(). create a Dog pet, use PrintInfo() to print information, and add a statement to print the dog's breed using the GetBreed() function. Ex. If the input is: Dobby2Kreacher3German Schnauzer the output is: Pet Information:    Name: Dobby   Age: 2Pet Information:    Name: Kreacher   Age: 3   Breed: German Schnauzer #include <iostream>#include<string>#include "Dog.h" using namespace std; int main() {     string petName, dogName, dogBreed;    int petAge, dogAge;     Pet myPet;    Dog myDog;     getline(cin, petName);    cin >> petAge;    cin.ignore();    getline(cin, dogName);    cin >> dogAge;    cin.ignore();    getline(cin, dogBreed);     // TODO: Create generic pet (using petName, petAge) and then call PrintInfo            //…
    6. Write an abstract class “Student” that has the attribute “name”, “id”, “cgpa”, totalFees.“Student” class has an abstract function fees(totalFees), concrete function toString().The fees function varies student to student. If any student has CGPA more than 3.90then he/she study with full free. If any student has CGPA more than 3.50 then he/sheget the 50% waiver of the total fees. The rest of the student have to pay the total fees.Design a JAVA class “CurrentStudent” that can be used in the “Student” class as localinner class to rewrite the given function. Also implement the system in main methodwith appropriate objects.
  • Define a member function PrintAll() for class PetData that prints output as follows with inputs "Fluffy", 5, and 4444. Hint: Make use of the base class' PrintAll() function.Name: Fluffy, Age: 5, ID: 4444  #include <string>using namespace std; class AnimalData {public:   void SetName(string givenName) {      fullName = givenName;   };   void SetAge(int numYears) {      ageYears = numYears;   };   // Other parts omitted    void PrintAll() {      cout << "Name: "  << fullName;      cout << ", Age: " << ageYears;   }; private:   int    ageYears;   string fullName;}; class PetData: public AnimalData {public:   void SetID(int petID) {      idNum = petID;   };    // FIXME: Add PrintAll() member function    /* Your solution goes here  */ private:   int idNum;}; int main() {   PetData userPet;   string userName;   int userAge;   int userID;    cin >> userName;   cin >> userAge;   cin >> userID;    userPet.SetName(userName);   userPet.SetAge…
    (Enhanced Employee Class) Modify class Employee inFigs. 12.9–12.10 by adding a private utility function calledisValidSocialSecurityNumber . This member function shouldvalidate the format of a social security number (e.g., ###-##-#### , where # is a digit). If the format is valid, return true ;otherwise return false .
    Define a class Distance with feet and inch and with a print function to print the distance. Write anon-member function (friend function) max which returns the larger of two distance objects, whichare arguments. Write a main program that accepts two distance objects from the user, comparethem and display the larger.
  • Define a member function PrintAll() for class PetData that prints output as follows with inputs "Fluffy", 5, and 4444. Hint: Make use of the base class' PrintAll() function. Name: Fluffy, Age: 5, ID: 4444 c++ code below, only lines 32-34 can be editted, the rest stays the same. #include <iostream>#include <string>using namespace std; class AnimalData {public:   void SetName(string givenName) {      fullName = givenName;   };   void SetAge(int numYears) {      ageYears = numYears;   };   // Other parts omitted    void PrintAll() {      cout << "Name: "  << fullName;      cout << ", Age: " << ageYears;   }; private:   int    ageYears;   string fullName;}; class PetData: public AnimalData {public:   void SetID(int petID) {      idNum = petID;   };    // FIXME: Add PrintAll() member function    /* Your solution goes here  */ private:   int idNum;}; int main() {   PetData userPet;   string userName;   int userAge;   int userID;    cin >> userName;…
    Define a member function PrintAll() for class PetData that prints output as follows with inputs "Fluffy", 5, and 4444. Hint: Make use of the base class' PrintAll() function.   Name: Fluffy, Age: 5, ID: 4444   c++ code below, only lines 32-34 can be editted, the rest stays the same.   #include <iostream> #include <string> using namespace std;   class AnimalData { public:    void SetName(string givenName) {       fullName = givenName;    };    void SetAge(int numYears) {       ageYears = numYears;    };    // Other parts omitted      void PrintAll() {       cout << "Name: " << fullName;       cout << ", Age: " << ageYears;    };   private:    int ageYears;    string fullName; };   class PetData: public AnimalData { public:    void SetID(int petID) {       idNum = petID;    };      // FIXME: Add PrintAll() member function      /* Your solution goes here */   private:    int idNum; };   int main() {    PetData userPet;    string userName;    int userAge;…
    Create a class Rectangle that has two data members, width and height, and two overloaded class member functions, drawshape() and drawshape(type width, type height). Show how function overloading of member function works in this class       b. In the main () function, show how the object of type Rectangle access. the overloaded function.
    • SEE MORE QUESTIONS
    Recommended textbooks for you
  • C++ Programming: From Problem Analysis to Program...
    Computer Science
    ISBN:9781337102087
    Author:D. S. Malik
    Publisher:Cengage Learning
    C++ for Engineers and Scientists
    Computer Science
    ISBN:9781133187844
    Author:Bronson, Gary J.
    Publisher:Course Technology Ptr
  • C++ Programming: From Problem Analysis to Program...
    Computer Science
    ISBN:9781337102087
    Author:D. S. Malik
    Publisher:Cengage Learning
    C++ for Engineers and Scientists
    Computer Science
    ISBN:9781133187844
    Author:Bronson, Gary J.
    Publisher:Course Technology Ptr
    Introduction to Classes and Objects - Part 1 (Data Structures & Algorithms #3); Author: CS Dojo;https://www.youtube.com/watch?v=8yjkWGRlUmY;License: Standard YouTube License, CC-BY