Cohoon & Davidson – Question 2.34

We all like to exercise because it’s good for us. Experts tell us that to get the maximum aerobic effect from exercise we should try to keep our pulse rate in a training zone. The training zone is computed as follows. Subtract your age from 220; 72% of that value is the low end of the range and 87% of that value is the high end of the range. Write a program that accepts an age and computes the training range.

Program:

// this program reads in an age and computes the training range

#include <iostream>

#include <string>

using namespace std;

int main(){

cout << "Enter your age: ";

int age;

cin >> age;

float LowEnd = (220 - age) * .72;

float HighEnd = (220 - age) * .87;

cout << "Your training range = " << LowEnd << ' - ' << HighEnd << endl;

return 0;

}

Output:

Enter your age: 27

Your training range = 138.96 - 167.91

Cohoon & Davidson – Question 3.22

Write a program that draws a tower consisting of five rectangles. The rectangles should be displayed in a window that is 8 centimetres wide and 10 centimetres high. The base rectangle should be 6 centimetres long and 1 centimetre high. Each succeeding rectangle is 75% of the length of the one underneath. The height of all the rectangles is the same. The rectangles should be blue.

Program:

// this program draws a rectangle tower

#include <iostream>

#include <string>

#include "ezwin.h"

#include "rect.h"

using namespace std;

int ApiMain(){

const int WinWidth = 8;

const int WinHeight = 10;

SimpleWindow W("Rectangle tower", WinWidth, WinHeight);

W.Open();

const float DecreaseFactor = 0.75;

float RectWidth = 6; // width changes

const int RectHeight = 1; // height doesn't change

float yPos = WinHeight - float(RectHeight / 2); // vertical pos changes

const int xPos = WinWidth / 2; // horizontal pos doesn't change

for (int i = 1; i <= 5; i++){

RectangleShape R(W, xPos, yPos, Blue, RectWidth, RectHeight);

R.Draw();

RectWidth *= DecreaseFactor;

yPos -= RectHeight;

}

char AnyChar;

cin >> AnyChar;

W.Close();

return 0;

}

Output:

Cohoon & Davidson – Question 3.31

Write a program that reads a name in the format

Tom Paris

and outputs it as

Paris, Tom

Note that you have to read both the name and surname as ONE string object. You may assume that the surname will not contain any spaces.

Program:

// this program reads in a name and displays it in another format

#include <iostream>

#include <string>

using namespace std;

int main(){

cout << "Enter your name: ";

string FullName;

getline(cin, FullName, '\n');

int SpacePosition = FullName.find(' ');

string FirstName = FullName.substr(0, SpacePosition);

string LastName = FullName.substr(SpacePosition + 1, FullName.size());

cout << LastName << ", " << FirstName << endl;

return 0;

}

Output:

Enter your name: Tom Paris

Paris, Tom

Cohoon & Davidson – Question 4.50

Write a C++ program that prompts and extracts from standard input a rectangle description and then displays the corresponding RectangleShape to a window that is 10cm wide and 10cm high. In reaction to a prompt, the user should provide the width and height of the rectangle, the x and y values that correspond to the centre of the rectangle, and the colour of the rectangle. The rectangle dimension and centre characteristics are given as floating point values; the colour of the rectangle is given as a character, either in lower case or upper case. A sample prompt and user response are given below:

Enter rectangle characteristics (w h x y colour):

that correspond to the centre of the rectangle, and the colour of the rectangle. The rectangle dimension and centre characteristics are given as floating point values; the colour of the rectangle is given as a character, either in lower case or upper case. A sample prompt and user response are given below:

Enter rectangle characteristics (w h x y colour):

4 5 2 2 r

Use a switch statement to convert the character representing the colour of the rectangle to a value of the enumerated type color, as required by RectangleShape.

Input

#include <iostream>

#include "rect.h"

using namespace std;

// this program displays a rectangle of dimensions specified

// by the user

int ApiMain(){

const int WinWidth = 10, WinHeight = 10;

cout << "Enter rectangle characteristics (w h x y colour): \n";

float w, h, x, y;

char ColourCode;

cin >> w >> h >> x >> y >> ColourCode;

color RColour;

// convert the character code to a colour:

switch(ColourCode){

case 'R': case 'r': RColour = Red; break;

case 'Y': case 'y': RColour = Yellow; break;

case 'B': case 'b': RColour = Black; break;

case 'W': case 'w': RColour = White; break;

case 'G': case 'g': RColour = Green; break;

case 'C': case 'c': RColour = Cyan; break;

case 'M': case 'm': RColour = Magenta; break;

default : RColour = Blue;

}

SimpleWindow Win ("A rectangle", WinWidth, WinHeight);

Win.Open();

RectangleShape R(Win, x, y, RColour, w, h);

R.Draw();

char AnyChar;

cin >> AnyChar;

Win.Close();

return 0;

}

Output

Enter rectangle characteristics (w h x y colour):

3 2 6 5 Y

Cohoon & Davidson – Question 4.58

Design and implement a program that extracts values from the standard input stream and then displays the smallest and largest of those values to the standard output stream. The program should display appropriate messages for special cases where there are no inputs and only one input.

Input

#include <iostream>

using namespace std;

// this program extracts values from the input stream and finds

// the smallest and largest of these

int main(){

cout << "This program will find the smallest and largest\n";

cout << "values of all the numbers you enter.\n";

cout << "Enter a list of integers (a character to stop):\n";

int n;

int Smallest, Largest;

// if the first value is an integer, initialise Smallest & Largest:

if (cin >> n){

Smallest = n;

Largest = n;

}

else {

// display an appropriate message if no values are entered:

cout << "No integers were entered" << endl;

return 1;

}

// compare every number read in to Smallest and Largest:

while (cin >> n){

if (n > Largest) Largest = n;

else if (n < Smallest) Smallest = n;

}

// display an appropriate message if only one value was entered:

if (Largest == Smallest){

cout << "The only number entered was " << n << endl;

}

// otherwise display the largest and smallest of all the values:

else{

cout << "Largest: " << Largest << " Smallest: " << Smallest << endl;

}

return 0;

}

Output

This program will find the smallest and largest

values of all the numbers you enter.

Enter a list of integers (a character to stop):

3 4 5 6 1 2

s

Largest: 6 Smallest: 1

C:\unisa\Cos112>

Cohoon & Davidson – Question 4.65

Design and implement a program that prompts its user for a non-negative value n. The program then displays as its output:

1 2 3 … n-1 n

1 2 3 … n-1

1 2 3

1 2

1

(Note: the …s are to be filled in with the appropriate numbers)

Input

#include <iostream>

#include <iomanip>

using namespace std;

// this program displays a triangle of size n (entered by the user)

int main(){

// get the triangle dimension from the user:

cout << "Enter a non-negative value: ";

int n;

cin >> n;

if (n <= 0){

cout << "The value was not non-negative\n";

return -1;

}

for (int i = 0; i < n; i++){ // each loop of i is a different row

int DisplayValue = 1; // each row starts with the value 1

for (int j = 0; j < n-i; j++){ // j represents the columns

cout << setw(3) << DisplayValue;

DisplayValue += 1; // column values increase from left to right

}

cout << endl; // at the end of each row, move to the next line

}

return 0;

}

Output

Enter a non-negative value: 10

1 2 3 4 5 6 7 8 9 10

1 2 3 4 5 6 7 8 9

1 2 3 4 5 6 7 8

1 2 3 4 5 6 7

1 2 3 4 5 6

1 2 3 4 5

1 2 3 4

1 2 3

1 2

1

Cohoon & Davidson – Question 6.73-75

Write a program that computes the difference between two times, both given in the following string format: hh:mm:ss by completing the following subtasks:

a) Write a function TimeToSeconds() that takes a single argument that represents a time in string format hh:mm:ss and returns the equivalent time in seconds. If this function receives an invalid time (e.g. 02:00:67) it should use the assert() function to report an error.

b) Write a function FormatTime() that takes a single parameter that is the time in seconds, and returns a string representing the time in the following format: hh:mm:ss.

c) Write a function ElapsedTime() that takes two parameters StartTime, EndTime, of type string in the same format as above and returns the difference between the two times. Your function should:

* Handle the case where StartTime is an optional parameter that should default to 00:00:00.

* Make use of the TimeToSeconds() function.

* Assert an error if StartTime or EndTime do not represent valid times or if StartTime is greater than EndTime.

Test your program with the following starting and ending times:

Start Time End Time

00:00:00 00:01:00

00:20:00 00:25:50

01:30:40 00:35:50

01:10:51 01:11:61

Input:

// main program, that uses functions to calculate the time difference:

#include "time.h" // includes all libraries needed

int main(){

cout << "Enter a start time (hh:mm:ss): ";

string StartTime;

cin >> StartTime;

cout << "Enter an end time (hh:mm:ss): ";

string EndTime;

cin >> EndTime;

cout << "The difference between these two times is "

<< ElapsedTime(EndTime, StartTime) << endl;

}

// header file, with libraries needed, global constants, and prototypes

#ifndef TIME_H

#define TIME_H

#include <iostream>

#include <string>

#include <cassert> // for assert()

#include <stdlib.h> // for atoi()

#include <strstream> // for ostrstream

#include <iomanip> // for setw() and setfill()

using namespace std;

// global constants:

const int SecondsInMinute = 60;

const int SecondsInHour = SecondsInMinute * 60;

// prototypes:

int TimeToSeconds(string);

string FormatTime(int);

string ElapsedTime(string, string);

#endif

// implementation (time.cpp) of the functions in the header file:

#include "time.h" // includes all libraries needed

int TimeToSeconds(string Time){

// check that the time has the correct length:

// assert() displays an error message if the expression is false

assert(Time.size() == 8);

// extract three parts and convert them to integers:

// also check that the values are within range:

int hh = atoi(Time.substr(0,2).c_str());

assert(hh >= 0 && hh < 24);

int mm = atoi(Time.substr(3,2).c_str());

assert(mm >= 0 && mm < 60);

int ss = atoi(Time.substr(6,2).c_str());

assert(ss >= 0 && ss < 60);

// calculate the total number of seconds and return:

return hh * SecondsInHour + mm * SecondsInMinute + ss;

}

string FormatTime(int Seconds){

// calculate hours, minutes & seconds and assign to variables:

int ss = Seconds % SecondsInMinute;

Seconds /= SecondsInMinute;

int mm = Seconds % SecondsInMinute;

Seconds /= SecondsInMinute;

int hh = Seconds;

// to store the time string, use an output stream buffer:

ostrstream TempOut;

// insert leading zeros if necessary, using setfill():

TempOut << setfill('0') << setw(2) << hh << ":";

TempOut << setw(2) << mm << ":";

TempOut << setw(2) << ss;

// access the total string with .str() and return:

return TempOut.str();

}

string ElapsedTime(string EndTime, string StartTime = "00:00:00"){

int StartSeconds = TimeToSeconds(StartTime);

int EndSeconds = TimeToSeconds(EndTime);

// the TimeToSeconds function will check if the times are valid

// check that start time is not greater than end time:

assert(StartSeconds <= EndSeconds);

int ElapsedSeconds = EndSeconds - StartSeconds;

return FormatTime(ElapsedSeconds);

}

Output:

Enter a start time (hh:mm:ss): 00:00:00

Enter an end time (hh:mm:ss): 00:01:00

The difference between these two times is 00:01:00

Enter a start time (hh:mm:ss): 00:20:00

Enter an end time (hh:mm:ss): 00:25:50

The difference between these two times is 00:05:50

Enter a start time (hh:mm:ss): 01:30:40

Enter an end time (hh:mm:ss): 00:35:50

Assertion failed: StartSeconds <= EndSeconds, file time.cpp, line 50

abnormal program termination

Enter a start time (hh:mm:ss): 01:10:51

Enter an end time (hh:mm:ss): 01:11:61

Assertion failed: ss >= 0 && ss < 60, file time.cpp, line 19

abnormal program termination

Cohoon & Davidson – Question 6.29

In the U.S. coin system, the penny is the basic coin, and it is equal to 1 cent, a nickel is equivalent to 5 cents, a dime is equivalent to 10 cents, a quarter is equivalent to 25 cents, and a half-dollar is equivalent to 50 cents. Write the following int functions. Each function has a single int formal parameter Amount.

a) HalfDollars(): Compute the maximum number of half-dollars that could be used in making change for Amount.

b) Quarters(): Compute the maximum number of quarters that could be used in making change for Amount.

c) Dimes(): Compute the maximum number of dimes that could be used in making change for Amount.

d) Nickels(): Compute the maximum number of nickels that could be used in making change for Amount.

Implement the required functions in a file called dollars.cpp. Also create a file dollars.h, which contains prototypes for all the functions.

dollars.cpp:

#include "dollars.h"

using namespace std;

int HalfDollars(int Amount){

return Amount / Half;

}

int Quarters(int Amount){

return Amount / Quarter;

}

int Dimes(int Amount){

return Amount / Dime;

}

int Nickels(int Amount){

return Amount / Nickel;

}

dollars.h:

// prototypes of functions implemented in dollars.cpp:

#ifndef DOLLARS_H

#define DOLLARS_H

using namespace std;

// global constants to be used in dollars.cpp and the main program:

const int Half = 50, Quarter = 25, Dime = 10, Nickel = 5;

int HalfDollars(int Amount);

int Quarters(int Amount);

int Dimes(int Amount);

int Nickels(int Amount);

#endif

Cohoon & Davidson – Question 6.30

Write a void function MakeChange() that expects a single int parameter Amount that displays to the standard output stream cout how to make change for Amount using a minimal number of U.S. coins. The function should use the functions developed in the previous question. Also develop a complete program that prompts a user for an amount, and if the amount is sensible, the program then invokes MakeChange(), using that amount as its actual parameter.

Implement the required function and main program in a separate file from dollars.cpp. The file should include the header file dollars.h, to make the required function prototypes visible.

// this program asks for an amount and calculates change for it