C++ Primer Plus Chapter 7 Exercise 7

c plus plus

This exercise makes use heavier use of pointers then what we have been doing. However, much of this program can be pulled from listing 7.7 and around that part of the chapter. See source below.

Redo Listing 7.7, modifying the three array-handling functions to each use two pointer parameters to represent a range. The fill_array() function, instead of returning the actual number of items read, should return a pointer to the location after the last location filled; the other functions can use this pointer as the second argument to identify the end of the data.

#include <iostream>

using namespace std;

const int Max = 5;

// function prototypes
double * fill_array(double *first, double *last);
void show_array(const double *first, const double *last);
void revalue(double *first, double *last, double factor);

int main()
{
double properties[Max];
double * last;

last = fill_array(properties, properties+Max);
show_array(properties, last);

cout << "Enter revaluation factor: ";
double factor;
cin >> factor;

revalue(properties, last, factor);
show_array(properties, last);
cout << "Done.\n";

return 0;
}

double *fill_array(double *first, double *last)
{
double temp;
double *pt;
int i=0;
for (pt = first; pt != last; pt++, i++)
{
cout << "Enter value #" << (i + 1) << ": ";
cin >> temp;
if (!cin) // bad input
{
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Bad input; input process terminated.\n";
break;
}
else if (temp < 0) // signal to terminate
break;
*pt = temp;
}
return pt;
}

void show_array(const double *first, const double *last)
{
const double *pt;
int i=0;
for (pt = first; pt != last; pt++, i++)
{
cout << "Property #" << (i + 1) << ": $ \n";
cout << *pt;
}
}

void revalue(double *first, double *last, double factor)
{
double *pt;
for (pt = first; pt != last; pt++)
*pt *= factor;
}

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s