Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition,
© 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3
Figure 3.3 Array Output Function |
void display(int theArray[], int numValues)
/*-----------------------------------------------------------------
Display values in an array of integers.
Precondition: 0 <= numValues < capacity of theArray.
Postcondition: The first numValues integers stored in theArray have
been output to cout.
-------------------------------------------------------------------------*/
{
for (int i = 0; i < n~~Values; i++)
cout « theArray[i] « 00 " .
cout « endl;
}
|
Figure 3.4 Array Input Function |
#include <cassert>
void read(IntArray theArray, int capacity, int numValues)
/*-------------------------------------------------------------------------
Input values into an array of integers from the keyboard.
Preconditions: 0 <= numValues < capacity, which is the capacity of theArray.
Postcondition: numValues integers entered from the keyboard
have been stored in the first NumValues positions of theArray
-------------------------------------------------------------------------/*
{
assert (numValues >= 0 && numValues <= capacity);
for (int i = 0; i < nurnValues; i++)
cin » theArray[i] ;
}
|
Figure
3.5 Demonstration of
|
/*--------------------------------------------------------------------------
Demonstration of what can happen when array indices get out of bounds.
Input: Three arrays of integers
Output: The three arrays before and after modification using
out-of-range indices.
-------------------------------------------------------------------------*/
#include <iostream>
using namespace std;
const int CAPACITY = 4;
typedef int IntArray[CAPACITY];
void read(IntArray theArray, int capacity, int numValues);
void display(IntArray theArray, int numValues);
int main()
{
IntArray a, b, c;
cout << "Enter " << CAPACITY << " integer values for:\n";
cout << "Array a: ";
read(a, CAPACITY, CAPACITY);
cout << "Array b: ";
read(b, CAPACITY, CAPACITY);
cout << "Array b: ";
read(c, CAPACITY, CAPACITY);
cout << "\n------ Part I of the demonstration -----\n\n"
"The arrays are:\n";
cout << "a: ";
display(a, CAPACITY);
cout << "b: ";
display(b, CAPACITY);
cout << "c: ";
display(c, CAPACITY);
//--- Now change array elements in b, but using
//--- some out-of-range indices.
int below = -3,
above = 6;
b[below] = -999;
b[above] = 999;
cout << "\n------ Part II of the demonstration -----\n\n"
"The arrays after out-of-range errors are:\n";
cout << "a: ";
display(a, CAPACITY);
cout << "b: ";
display(b, CAPACITY);
cout << "c: ";
display(c, CAPACITY);
cout << endl;
return 0;
}
//--- Insert here the definition of read() from Figure 3-4
//--- and the definition of display() from Figure 3-3
//--- Definitions of array i/o functions
#include <cassert>
void read(IntArray theArray, int capacity, int numValues)
/*-------------------------------------------------------------------------
Input values into an array of integers from the keyboard.
Preconditions: 0 <= numValues < capacity, which is the capacity of
theArray.
Postcondition: numValues integers entered from the keyboard have been
stored in the first numValues positions of theArray.
-------------------------------------------------------------------------*/
{
assert (numValues >= 0 && numValues <= capacity);
for (int i = 0; i < numValues; i++)
cin >> theArray[i];
}
void display(int theArray[], int numValues)
/*-------------------------------------------------------------------------
Display values in an array of integers.
Precondition: 0 <= numValues < capacity of theArray.
Postcondition: The first numValues integers stored in theArray have
been output to cout.
-------------------------------------------------------------------------*/
{
for (int i = 0; i < numValues; i++)
cout << theArray[i] << " ";
cout << endl;
}
|
Figure 3.8 Failure of new -- Version 1 |
//-- Demonstration #1 of new failure -- Uncaught bad_alloc exception
#include <iostream>
#include <new> // new, bad_alloc
using namespace std;
int main()
{
const int NUM_ARRAYS = 10;
cout << "How large should the arrays of doubles be? ";
int capacity;
cin >> capacity;
double * arrayPtr[NUM_ARRAYS];
int i;
for (i = 0; i < NUM_ARRAYS; i++)
{
arrayPtr[i] = new double [capacity];
cout << "Allocated " << capacity
<< " doubles for i = " << i << endl;
}
cout << "All " << NUM_ARRAYS << " arrays of "
<< capacity << " doubles were allocated successfully." << endl;
}
|
Figure 3.9 Failure of new -- Version 2 |
//-- Demonstration #2 of new failure -- Use try-catch mechanixm
//-- to handle bad_alloc exception.
#include <iostream>
#include <new>
using namespace std;
int main()
{
const int NUM_ARRAYS = 10;
cout << "How large should the arrays of doubles be? ";
int capacity;
cin >> capacity;
double * arrayPtr[NUM_ARRAYS];
int i;
try
{
for (i = 0; i < NUM_ARRAYS; i++)
{
arrayPtr[i] = new double [capacity];
cout << "Allocated " << capacity
<< " doubles for i = " << i << endl;
}
}
catch (bad_alloc ex)
{
cout << "\nException: " << ex.what()
<< " -- for i = " << i << endl;
exit(1);
}
cout << "All " << NUM_ARRAYS << " arrays of "
<< capacity << " doubles were allocated successfully." << endl;
}
|
Figure
3.11a Time Data Type
|
/*== Time.h ===============================================================
This header file defines the data type Time for processing time.
Basic operations are:
set: To set the time
display: To display the time
advance: To advance the time by a certain amount
lessThan: To determine if one time is less than another
=========================================================================*/
#include <iostream>
using namespace std;
struct Time
{
unsigned hour,
minute;
char AMorPM; // 'A' or 'P'
unsigned milTime; // military time equivalent
};
void set(Time & t, unsigned hours, unsigned minutes, char AMPM);
/*-------------------------------------------------------------------------
Set the time to a specified value.
Receive: Time object t
hours, the number of hours in standard time
minutes, the number of minutes in standard time
AMPM ('A' if AM, 'P' if PM)
Pass back: The modified Time t with data members set to the
specified values
-------------------------------------------------------------------------*/
void display(const Time & t, ostream & out);
/*-------------------------------------------------------------------------
Display time t in standard and military format using output stream out.
Receive: Time t and ostream out
Output: The time t to out
Pass back: The modified ostream out with a representation of t
inserted into it
------------------------------------------------------------------------*/
void advance(Time & t, unsigned hours, unsigned minutes);
/*-------------------------------------------------------------------------
Increment a time by a specified value.
Receive: Time object t
hours, the number of hours to add
minutes, the number of minutes to add
Pass back: The modified Time t with data members incremented by the
specified values
-------------------------------------------------------------------------*/
bool lessThan(const Time & t1, const Time & t2);
/*-------------------------------------------------------------------------
/* Determines if one time is less than another time.
*
* Receive: Times t1 and t2
* Return: True if t1 < t2, false otherwise.
-------------------------------------------------------------------------*/
|
Figure 3.11b Time.cpp |
/*== Time.cpp =============================================================
Implementations of the function members of class Time.
Prototypes are in Time.h.
========================================================================*/
#include "Time.h"
/** Utility functions -- might be added as basic operations later **/
int toMilitary(unsigned hours, unsigned minutes, char AMPM);
void toStandard(unsigned military,
unsigned & hours, unsigned & minutes, char & AMPM);
//--- Definition of set() -------------------------------------------------
void set(Time & t, unsigned hours, unsigned minutes, char AMPM)
{
if (hours >= 1 && hours <= 12 &&
minutes >= 0 && minutes <= 59 &&
(AMPM == 'A' || AMPM == 'P'))
{
t.hour = hours;
t.minute = minutes;
t.AMorPM = AMPM;
t.milTime = toMilitary(hours, minutes, AMPM);
}
else
cerr << "*** Can't set time with these values ***\n";
// t remains unchanged
}
//--- Definition of display() ---------------------------------------------
void display(const Time & t, ostream & out)
{
out << t.hour << ':'
<< (t.minute < 10 ? "0" : "") << t.minute
<< ' ' << t.AMorPM << ".M. ("
<< t.milTime << " mil. time)";
}
//--- Definition of advance() ---------------------------------------------
void advance(Time & t, unsigned hours, unsigned minutes)
{
// Advance using military time
t.milTime += 100 * hours + minutes;
unsigned milHours = t.milTime / 100,
milMins = t.milTime % 100;
// Adjust to proper format
milHours += milMins / 60;
milMins %= 60;
milHours %= 24;
t.milTime = 100 * milHours + milMins;
// Now set standard time
toStandard(t.milTime, t.hour, t.minute, t.AMorPM);
}
//--- Definition of lessThan() --------------------------------------------
bool lessThan(const Time & t1, const Time & t2)
{
return (t1.milTime < t2.milTime);
}
//----- DEFINITIONS OF UTILITY FUNCTIONS -------
int toMilitary (unsigned hours, unsigned minutes, char AMPM)
/*-------------------------------------------------------------------------
Convert standard time to military time.
Receive: hours, minutes, AMPM
Return: The military time equivalent
-------------------------------------------------------------------------*/
{
if (hours == 12)
hours = 0;
return hours * 100 + minutes + (AMPM == 'P' ? 1200 : 0);
}
void toStandard(unsigned military,
unsigned & hours, unsigned & minutes, char & AMPM)
/*-------------------------------------------------------------------------
Convert military time to standard time.
Receive: military, a time in military format
Return: hours, minutes, AMPM -- equivalent standard time
-------------------------------------------------------------------------*/
{
hours = (military / 100) % 12;
if (hours == 0)
hours = 12;
minutes = military % 100;
AMPM = (military / 100) < 12 ? 'A' : 'P';
}
|
Parameters with Multi-Dimensional Arrays |
const int NUM_ROWS = 30, NUM_COLUMNS = 5 ;
typedef double TwoDimArray[NUM_ROWS] [NUM_COLUMNS] ;
void display(TwoDimArray the2DArray, int rowsUsed, int colurnnsUsed) ;
int main()
{
TwoDimArray scoresTable ;
// -- Statements to input scores into scoresTable
display(scoresTable, int nurnStudents, numTests)
}
|
Figure 3.11c Driver |
/*== Driver ==============================================================
Driver program to test Time library.
========================================================================*/
#include "Time.h"
#include <iostream>
#include <iostream>
using namespace std;
int main()
{
Time mealTime,
goToWorkTime;
set(mealTime, 5, 30, 'P');
cout << "We'll be eating at ";
display(mealTime, cout);
cout << endl;
set(goToWorkTime, 5, 30, 'P'); // Try other values also: 'A' -> 'P'
cout << "You leave for work at ";
display(goToWorkTime, cout);
cout << endl;
if (lessThan(mealTime, goToWorkTime))
cout << "If you hurry, you can eat first.\n";
else
cout << "Sorry you can't eat with us.\n";
advance(goToWorkTime, 0, 30); // Try other values also: 0 -> 12)
cout << "Your boss called. You go in later at ";
display(goToWorkTime, cout);
cout << endl;
if (lessThan(mealTime, goToWorkTime))
cout << "If you hurry, you can eat first.\n";
else
cout << "Sorry you can't eat with us.\n";
cout << endl;
}
|