Вы находитесь на странице: 1из 36

1.

Write a program that repeatedly asks the user to enter pairs of numbers until at least one
of the pair is 0. For each pair, the program should use a function to calculate the harmonic
mean of the numbers. The function should return the answer to main(), which
should report the result. The harmonic mean of the numbers is the inverse of the average
of the inverses and can be calculated as follows:
harmonic mean = 2.0 x y / (x + y)
My Answer:
#include <iostream>

double mean (double, double);

int main()
{

using namespace std;

cout << "Enter pair of numbers (0 to stop): ";


double x,y;

while (cin >> x >> y)


{
if (x == 0 || y == 0)
break;

cout << "The harmonic mean of " << x << " and " << y << " is " << mean(x,y);
cout << "\n\nNext pair of numbers (0 to stop): ";
}

cout << "\nBye!";


cin.get();
cin.get();
return 0;
}

double mean(double x, double y)


{
float meanV = 0;

meanV = (2.0 * x * y) / (x + y);

return meanV;
}

2 Responses to C++ Primer Plus Chapter 7 Exercise 1 Answer

1.

Freddy says:
October 26, 2011 at 9:45 am
For line 10 it says that the identifier cout is unidentified & for line 13, it says that
identifier cin is unidentified
Reply

Daniel says:
March 27, 2013 at 3:11 pm
using namespace std; & iostream??

2. Write a program that asks the user to enter up to 10 golf scores, which are to be stored
in an array. You should provide a means for the user to terminate input prior to entering
10 scores. The program should display all the scores on one line and report the average
score. Handle input, display, and the average calculation with three separate arrayprocessing
functions.
My Answer:
1 #include <iostream>
2
3 const int mysize = 10;

4 void inputscores (int *, int);


5 void displayinput (int *, int);
6 double average (const int *, int);
7
8 int main()
9 {
10
11using namespace std;
12
13int golfscores[mysize];
14int * gs = golfscores;
15
16inputscores(gs,mysize);
17displayinput(gs,mysize);
18cout << "\nThe average is " << average(gs,mysize);
19
20cin.get();
21cin.get();
22return 0;
23}
24
25void inputscores (int *ar, int arsize)
26{
27 std::cout << "Enter " << arsize << " score(s). Type -1 to exit.\n";
28 int failflag = 1;
29 for (int i=0; i < arsize; i++)
30 {
31

if (failflag != 0)

32

33

std::cout << "Score #" << i+1 << ": ";

34

(std::cin >> ar[i]).get();

35

36

if (ar[i] == -1)

37

failflag = 0;

38 }
39}
40
41void displayinput (int *ar, int arsize)
42{
43 std::cout << "\nDisplaying input on one line: ";
44 for (int i=0; i < arsize && (ar[i] != -1); i++)
45

std::cout << ar[i];

46}
47
48double average (const int *ar, int arsize)
49{
50 double avg = 0;
51 double total = 0;
52 int elements = 0;
53
54 for (int i=0; i < arsize && (ar[i] != -1); i++)
55 {
56

total = total + ar[i];

57

elements++;

58 }
59
60 std::cout << "\nTotal = " << total;
61 std::cout << "\nElements = " << elements;
62 avg = total / elements;
63 return avg;
64}

One Response to C++ Primer Plus Chapter 7 Exercise 2 Answer

1.

Saad says:
January 31, 2012 at 12:45 pm
// C++ Primer Plus Exercise
// Chapter 7, Exercise 2
#include
//- Function Prototyping
void input(int []);
double average(int[]);
void display(int[]);
//
int main()
{
using namespace std;
int scores[10]={};
input(scores);
display(scores);
if(average(scores))
cout << "\n Average score: " << average(scores);
return 0;
}
//- Function(s)
//+ Input
void input(int scores[])
{
int buffer = 0;
std::cout << "Please enter scores, maximum of 10 (-ve number to quit)\n";
for(int i=0; i<10; i++)
{
std::cout << "#" << i+1 <> buffer)
{
if(buffer<0)
{
std::cout << "Terminating due to -ve input, " << i << " score(s) read\n";
break;
}

else
scores[i] = buffer;
}
else
{
std::cout << "\nInvalid input, terminating";
std::cin.clear();
std::cin.get();
break;
}
}
}
//++
//+ Average
double average(int scores[])
{
double total = 0;
int counter = 0;
for(int i=0; i<10; i++)
{
if(scores[i]=='' && i==0)
{
std::cout << "\nThe score card appears to be empty, no average to report.";
return 0;
}
else if(scores[i] != '')
{
total += scores[i];
counter++;
}
}
return (total/counter);
}
//++
//+ Display
void display(int scores[])
{
for(int i=0; i<10; i++)
{
if(scores[i]=='' || i==10)
{
if(i == 0)
{
std::cout << "\nScore card appears to be empty exiting";
break;
}
else

{
std::cout << "\nEnd of score card reached at entry #" << i;
break;
}
}
std::cout << "#" << i+1 << ": " << scores[i] << "\t";
}
}
//++
//

3. Here is a structure declaration:


struct box
{
char maker[40];
float height;
float width;
float length;
float volume;
};
a. Write a function that passes a box structure by value and that displays the value of
each member.
b. Write a function that passes the address of a box structure and that sets the volume
member to the product of the other three dimensions.
c. Write a simple program that uses these two functions.
My Answer:
1 #include <iostream>
2
3 struct box
4 {
5 char maker[40];
6 float height;
7 float width;
8 float length;
9 float volume;
10};
11
12void displaystruct (box);

13void setvolume(box *);


14
15int main()
16{
17
18using namespace std;
19
20box PaperMaker = {"PaperProBox",2.5,3.6,5.6,0};
21
22displaystruct(PaperMaker);
23setvolume(&PaperMaker);
24displaystruct(PaperMaker);
25
26cin.get();
27cin.get();
28return 0;
29}
30
31void displaystruct (box Mystruct)
32{
33 using namespace std;
34 cout << "\nDisplaying structure content:\n";
35 cout << "-----------------------------";
36 cout << "\nMaker is " << Mystruct.maker;
37 cout << "\nHeight is " << Mystruct.height;
38 cout << "\nWidth is " << Mystruct.width;
39 cout << "\nLength is " << Mystruct.length;
40 cout << "\nVolume is " << Mystruct.volume;
41}
42
43void setvolume (box * Mystruct)

44{
45 Mystruct->volume = Mystruct->height*Mystruct->width*Mystruct->length;
46}

4. Many state lotteries use a variation of the simple lottery portrayed by Listing 7.4. In
these variations you choose several numbers from one set and call them the field numbers.
For example, you might select 5 numbers from the field of 147). You also pick a
single number (called a mega number or a power ball, etc.) from a second range, such as
127. To win the grand prize, you have to guess all the picks correctly. The chance of
winning is the product of the probability of picking all the field numbers times the probability
of picking the mega number. For instance, the probability of winning the example
described here is the product of the probability of picking 5 out of 47 correctly times the
probability of picking 1 out of 27 correctly. Modify Listing 7.4 to calculate the probability
of winning this kind of lottery.
My Answer:
1 #include <iostream>
2
3 long double probability(unsigned numbers, unsigned picks);
4 double lotterychance(int, int, int, int, long double (*pb)(unsigned, unsigned));
5
6 int main()
7 {
8 using namespace std;
9
10cout << "The lottery chance of winning state lottery is ";
11cout << lotterychance(47,5,27,1,probability);
12
13cout << "bye\n";
14cin.get();
15cin.get();
16return 0;
17}
18// the following function calculates the probability of picking picks
19// numbers correctly from numbers choices

20long double probability(unsigned numbers, unsigned picks)


21{
22long double result = 1.0; // here come some local variables
23long double n;
24unsigned p;
25for (n = numbers, p = picks; p > 0; n--, p--)
26result = result * n / p ;
27return result;
28}
29
30double lotterychance(int field, int fieldselect, int meganum, int megaselect, long double
(*pb)(unsigned, unsigned))
31
{
32
double chance;
33
34
35

chance = pb(field,fieldselect)*pb(meganum,megaselect);

36
37
}

return chance;

5. Define a recursive function that takes an integer argument and returns the factorial of
that argument. Recall that 3 factorial, written 3!, equals 3 2!, and so on, with 0!
defined as 1. In general, if n is greater than zero, n! = n * (n 1)!. Test your function in a
program that uses a loop to allow the user to enter various values for which the program
reports the factorial.
My Answers:
1 #include <iostream>
2
3 int factorial (int);
4
5 int main()
6 {

7 using namespace std;


8
9 int fact = 0;
10
11cout << "Enter factorials (-1 to stop): ";
12while ((cin >> fact).get() && fact != -1)
13{
14 cout << "\nThe factorial of " << fact << "! is " << factorial(fact) << endl;
15}
16
17cout << "\nBye!";
18cin.get();
19cin.get();
20return 0;
21}
22
23int factorial (int number)
24{
25 int factor = 1;
26
27
28 if (number > 0 )
29 {
30

factor = number * factorial(number-1);

31 }
32
33 return factor;
34}

2 Responses to C++ Primer Plus Chapter 7 Exercise 5 Answer

1.

Fran says:
July 27, 2012 at 10:21 am
Define a recursive function
Your function doesnt call itself.
I did something like this:
int Factorial(int res, int n, int c)
{
while (c < n)
{
c++;
res *= c;
Factorial(res, n, c);
}
return res;
}
Reply

2.

Daniel says:
March 27, 2013 at 5:16 pm
i think we can use a better way to realize the factorial by using the tail recursion:
int factorial (int number,int acc)
// acc is an accumulator to record the each computing n*(n-1)
// so acc shall be initialized as 1
{
if (number==0) return acc;
return factorial(number-1,number*acc);
}

6. Write a program that uses the following functions:


Fill_array() takes as arguments the name of an array of double values and an array
size. It prompts the user to enter double values to be entered in the array. It ceases taking
input when the array is full or when the user enters non-numeric input, and it
returns the actual number of entries.
Show_array() takes as arguments the name of an array of double values and an array
size and displays the contents of the array.
Reverse_array() takes as arguments the name of an array of double values and an

array size and reverses the order of the values stored in the array.
The program should use these functions to fill an array, show the array, reverse the array,
show the array, reverse all but the first and last elements of the array, and then show the
array.
My Answers:
1 #include <iostream>
2
3 const int mysize = 7;
4 int Fill_array (double [], int);
5 void Show_array (double [], int);
6 void Reverse_array (double [], int, bool);
7
8 int main()
9 {
10using namespace std;
11
12double ar[mysize];
13int actualsize = 0;
14
15actualsize = Fill_array(ar,mysize);
16Show_array(ar,actualsize);
17Reverse_array(ar,actualsize,false);
18Show_array(ar,actualsize);
19Reverse_array(ar,actualsize,true);
20Show_array(ar,actualsize);
21
22cin.get();
23cin.get();
24return 0;
25}
26
27int Fill_array (double ar[], int arsize)

28{
29 using namespace std;
30 int entries = 0;
31 double temp;
32 bool endflag = false;
33 cout << "\nFilling Array: " << endl;
34
35 for (int i=0; i < arsize && endflag == false; i++)
36 {
37

cout << "Element #" << i+1 << ": ";

38

if (!(cin >> temp))

39

40

ar[i]=0;

41

cin.clear();

42

cin.get();

43

cin.get();

44

cout << "\n----Entry has ended.---\n";

45

endflag = true;

46
47

48

else

49

50

ar[i] = temp;

51

entries++;

52

53 }
54
55 return entries;
56}
57
58void Show_array (double ar[], int arsize)

59{
60 std::cout << "\nShowing Array: " << std::endl;
61 for (int i=0; i < arsize; i++)
62

std::cout << "Element #" << i+1 << ": " << ar[i] << std::endl;

63}
64
65void Reverse_array (double ar[], int arsize, bool firstlast)
66{
67 double * temp = new double [arsize];
68
69 for (int i=0; i < arsize; i++)
70

temp[i] = ar[i];

71
72 for (int j=0; j < arsize; j++)
73 {
74

if (firstlast == true && ( j == 0 || j == (arsize-1)))

75

continue;

76

else

77

ar[j] = temp[arsize-(j+1)];

78 }
79
80 delete [] temp;
81
82 std::cout << "\nArray Reverse is done.\n";
83}

4 Responses to C++ Primer Plus Chapter 7 Exercise 6 Answer

1.

Saad says:
February 6, 2012 at 8:43 pm

// C++ Primer Plus Exercise


// Chapter 7, Exercise 6
#include
//- Function(s) Prototype
int fillArray(double [], int);
void showArray(double [], int);
void reverseArray(double [], int);
//
int main()
{
using namespace std;
double data[10];
int count=0;
// double *pArray = data;
count = fillArray(data, 10);
cout << count << " items filled in array\n";
showArray(data, count);
reverseArray(data, count);
showArray(data, count);
return 0;
}
//- Function(s)
int fillArray(double array[], int size)
{
double input;
int i;
for(i=0; i<size; i++)
{
std::cout << "Enter item #"<< i+1 <> input;
if(std::cin.fail())
{
std::cin.clear();
std::cin.get();
std::cout << "Bad Input; Process Terminated.\n";
break;
}
array[i] = input;
}

return i;
}
void showArray(double array[], int size)
{
for(int i=0; i<size; i++)
{
std::cout << "Item #"<< i+1 << " " << array[i] << "\n";
}
}
void reverseArray(double array[], int size)
{
double temp;// = array[size-1];
for(int i=0, j=size-1; i<j; i++, j)
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
//
Reply

2.

Yechiel Labunskiy says:


July 5, 2012 at 8:48 pm
Heres a simpler version, without having to use bool etc.
Code Snippet

<div class="le-cah-container">
<div class="le-cah-titleblock">Code Snippet</div>
<div style="background: #ddd; max-height: 300px; overflow: auto">
<ol start="1" style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;">
<li><span style="color:#008000">// Ch. 7.6 ReverseArray and ReverseArray
except the first and last value using the same function</span></li>
<li style="background: #f3f3f3">&nbsp;</li>
<li><span style="color:#0000ff">#include</span> <span
style="color:#a31515">&quot;stdafx.h&quot;</span></li>
<li style="background: #f3f3f3"><span style="color:#0000ff">#include</span>
<span style="color:#a31515">&lt;iostream&gt;</span></li>
<li><span style="color:#0000ff">using</span> <span
style="color:#0000ff">namespace</span> std;</li>

<li style="background: #f3f3f3">&nbsp;</li>


<li><span style="color:#0000ff">int</span> fillArray(<span
style="color:#0000ff">double</span> *a, <span style="color:#0000ff">int</span>
size);</li>
<li style="background: #f3f3f3"><span style="color:#0000ff">void</span>
showArray(<span style="color:#0000ff">double</span> *a, <span
style="color:#0000ff">int</span> size);</li>
<li><span style="color:#0000ff">void</span> reverseArray(<span
style="color:#0000ff">double</span> *a, <span style="color:#0000ff">int</span>
size);</li>
<li style="background: #f3f3f3">&nbsp;</li>
<li><span style="color:#0000ff">int</span> _tmain(<span
style="color:#0000ff">int</span> argc, _TCHAR* argv[])</li>
<li style="background: #f3f3f3">{</li>
<li> <span style="color:#0000ff">int</span> size=10;</li>
<li style="background: #f3f3f3"> <span style="color:#0000ff">double</span>
a[10];</li>
<li>&nbsp;</li>
<li style="background: #f3f3f3"> cout&lt;&lt;<span
style="color:#a31515">&quot;Please enter up to 10 numbers to fill an array. Enter
non-numeric input to stop: \n&quot;</span>;</li>
<li> size=fillArray(a, size);</li>
<li style="background: #f3f3f3">&nbsp;</li>
<li> cout&lt;&lt;<span style="color:#a31515">&quot;Here's your array:
\n&quot;</span>;</li>
<li style="background: #f3f3f3"> showArray(a, size);</li>
<li>&nbsp;</li>
<li style="background: #f3f3f3"> cout&lt;&lt;<span
style="color:#a31515">&quot;Here's your array reversed: \n&quot;</span>;</li>
<li> reverseArray(a, size);</li>
<li style="background: #f3f3f3"> showArray(a, size);</li>
<li> reverseArray(a, size);</li>
<li style="background: #f3f3f3">&nbsp;</li>
<li> cout&lt;&lt;<span style="color:#a31515">&quot;Here's your array with all but
the first and last numbers reversed: \n&quot;</span>;</li>
<li style="background: #f3f3f3"> reverseArray(a+1, size-2); <span
style="color:#008000">// a+1 moves the start of the array to the 1st element, size-2
moves the end of the array to the second to last element (-2 since a was moved
+1)</span></li>
<li> showArray(a, size);</li>
<li style="background: #f3f3f3">&nbsp;</li>
<li> <span style="color:#0000ff">return</span> 0;</li>
<li style="background: #f3f3f3">}</li>
<li>&nbsp;</li>
<li style="background: #f3f3f3"><span style="color:#0000ff">int</span>
fillArray(<span style="color:#0000ff">double</span> *a, <span
style="color:#0000ff">int</span> size)</li>
<li>{</li>
<li style="background: #f3f3f3"> <span style="color:#0000ff">int</span> i;</li>
<li> <span style="color:#0000ff">for</span> (i=0; i&lt;size &amp;&amp;

cin&gt;&gt;a[i]; i++);</li>
<li style="background: #f3f3f3"> <span style="color:#0000ff">return</span>
i;</li>
<li>}</li>
<li style="background: #f3f3f3">&nbsp;</li>
<li><span style="color:#0000ff">void</span> showArray(<span
style="color:#0000ff">double</span> *a, <span style="color:#0000ff">int</span>
size)</li>
<li style="background: #f3f3f3">{</li>
<li> <span style="color:#0000ff">for</span> (<span
style="color:#0000ff">int</span> i=0; i&lt;size; i++)</li>
<li style="background: #f3f3f3">
cout&lt;&lt;a[i]&lt;&lt;<span
style="color:#a31515">' '</span>;</li>
<li> cout&lt;&lt;endl;</li>
<li style="background: #f3f3f3">}</li>
<li>&nbsp;</li>
<li style="background: #f3f3f3"><span style="color:#0000ff">void</span>
reverseArray(<span style="color:#0000ff">double</span> *a, <span
style="color:#0000ff">int</span> size)</li>
<li>{</li>
<li style="background: #f3f3f3"> <span style="color:#0000ff">double</span>
hold;</li>
<li> <span style="color:#0000ff">int</span> i, j;</li>
<li style="background: #f3f3f3"> <span style="color:#0000ff">for</span> (i=0,
j=size-1; i&lt;j; i++, j)</li>
<li> {</li>
<li style="background: #f3f3f3">
hold=a[i];</li>
<li>
a[i]=a[j];</li>
<li style="background: #f3f3f3">
a[j]=hold;</li>
<li> }</li>
<li style="background: #f3f3f3">}</li>
</ol>
</div>
</div>
Reply

3.

Yechiel Labunskiy says:


July 5, 2012 at 8:49 pm
Heres a simpler version without having to use bool:
Code Snippet
// Ch. 7.6 ReverseArray and ReverseArray except the first and last value using the
same function
#include "stdafx.h"

#include <iostream>
using namespace std;
int fillArray(double *a, int size);
void showArray(double *a, int size);
void reverseArray(double *a, int size);
int _tmain(int argc, _TCHAR* argv[])
{
int size=10;
double a[10];
cout<<"Please enter up to 10 numbers to fill an array. Enter non-numeric input to
stop: \n";
size=fillArray(a, size);
cout<<"Here's your array: \n";
showArray(a, size);
cout<<"Here's your array reversed: \n";
reverseArray(a, size);
showArray(a, size);
reverseArray(a, size);
cout<<"Here's your array with all but the first and last numbers reversed: \n";
reverseArray(a+1, size-2); // a+1 moves the start of the array to the 1st element,
size-2 moves the end of the array to the second to last element (-2 since a was
moved +1)
showArray(a, size);
return 0;
}
int fillArray(double *a, int size)
{
int i;
for (i=0; i<size && cin>>a[i]; i++);
return i;
}
void showArray(double *a, int size)
{
for (int i=0; i<size; i++)
cout<<a[i]<<' ';
cout<<endl;
}
void reverseArray(double *a, int size)
{
double hold;

int i, j;
for (i=0, j=size-1; i<j; i++, j)
{
hold=a[i];
a[i]=a[j];
a[j]=hold;
}
}
Reply

4.

Yechiel Labunskiy says:


July 5, 2012 at 8:53 pm
Sorry about that first post. How can I copy/paste the code so that it will appear just
like in visual studio? With the colors and everything.

7. 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.
1 #include <iostream>
2 const int Max = 5;
3
4 double * fill_array(double * begin, double * end);
5 void show_array(const double * begin, const double * end);
6 void revalue(double factor, double * begin, double * end);
7
8 int main()
9 {
10using namespace std;
11double properties[Max];
12double * size = fill_array(properties, properties + Max);

13
14show_array(properties, size);
15cout << "Enter revaluation factor: ";
16
17double factor;
18cin >> factor;
19
20revalue(factor, properties, size);
21show_array(properties, size);
22
23
24cout << "Done.\n";
25cin.get();
26cin.get();
27return 0;
28}
29
30double * fill_array(double * begin, double * end)
31{
32 using namespace std;
33 double temp;
34 int i=0;
35 for (begin; begin < end; begin++)
36 {
37

cout << "Enter value #" << (i + 1) << ": ";

38

cin >> temp;

39 if (!cin) // bad input


40 {
41

cin.clear();

42 while (cin.get() != '\n')


43

continue;

44 cout << "Bad input; input process terminated.\n";


45 break;
46 }
47 else if (temp < 0) // signal to terminate
48

break;

49 * begin = temp;
50 i++;
51 }
52 return begin;
53}
54
55// the following function can use, but not alter,
56// the array whose address is ar
57void show_array(const double * begin, const double * end)
58{
59 using namespace std;
60 int i = 0;
61 for (begin; begin < end; begin++)
62 {
63

cout << "Property #" << (i + 1) << ": $";

64

cout << *begin << endl;

65

i++;

66 }
67}
68
69// multiplies each element of ar[] by r
70void revalue(double factor, double * begin, double * end)
71{
72 for (begin; begin < end; begin++)
73 * begin *= factor;
74}

8. This exercise provides practice in writing functions dealing with arrays and structures.
The following is a program skeleton. Complete it by providing the described functions:
#include
using namespace std;
const int SLEN = 30;
struct student {
char fullname[SLEN];
char hobby[SLEN];
int ooplevel;
};
// getinfo() has two arguments: a pointer to the first element of
// an array of student structures and an int representing the
// number of elements of the array. The function solicits and
// stores data about students. It terminates input upon filling
// the array or upon encountering a blank line for the student
// name. The function returns the actual number of array elements
// filled.
int getinfo(student pa[], int n);
// display1() takes a student structure as an argument
// and displays its contents
void display1(student st);
// display2() takes the address of student structure as an
// argument and displays the structures contents
void display2(const student * ps);
// display3() takes the address of the first element of an array
// of student structures and the number of array elements as
// arguments and displays the contents of the structures
void display3(const student pa[], int n);
int main()
{
cout << Enter class size: ;
int class_size;
cin >> class_size;
while (cin.get() != \n)
continue;
student * ptr_stu = new student[class_size];
int entered = getinfo(ptr_stu, class_size);
for (int i = 0; i < entered; i++)
{
display1(ptr_stu[i]);
display2(&ptr_stu[i]);
}
display3(ptr_stu, entered);
delete [] ptr_stu;
cout << Done\n;

return 0;
}
My Answer:
1

#include <iostream>

2
3

using namespace std;

4
5

const int SLEN = 30;

6
7

struct student {

char fullname[SLEN];

char hobby[SLEN];

10 int ooplevel;
11 };
12
13 // getinfo() has two arguments: a pointer to the first element of
14 // an array of student structures and an int representing the
15 // number of elements of the array. The function solicits and
16 // stores data about students. It terminates input upon filling
17 // the array or upon encountering a blank line for the student
18 // name. The function returns the actual number of array elements
19 // filled.
20 int getinfo(student pa[], int n);
21 // display1() takes a student structure as an argument
22 // and displays its contents
23 void display1(student st);
24 // display2() takes the address of student structure as an
25 // argument and displays the structures contents
26 void display2(const student * ps);
27 // display3() takes the address of the first element of an array
28 // of student structures and the number of array elements as

29 // arguments and displays the contents of the structures


30 void display3(const student pa[], int n);
31
32 int main()
33 {
34
35 cout << "Enter class size: ";
36 int class_size;
37 cin >> class_size;
38
39 while (cin.get() != '\n')
40

continue;

41
42 student * ptr_stu = new student[class_size];
43 int entered = getinfo(ptr_stu, class_size);
44 for (int i = 0; i < entered; i++)
45 {
46

display1(ptr_stu[i]);

47

display2(&ptr_stu[i]);

48 }
49
50 display3(ptr_stu, entered);
51
52 delete [] ptr_stu;
53 cout << "\nDone";
54
55 cin.get();
56 cin.get();
57 return 0;
58 }
59

60 int getinfo(student pa[], int n)


61 {
62

int i;

63

for (i = 0; i < n; i++)

64

65

cout << "\nStudent #" << (i+1);

66

cout << "\nName: ";

67

cin.getline(pa[i].fullname,SLEN);

68

if (pa[i].fullname[0] == '\0')

69

70

cout << "Oops...you've entered empty line for name..terminating";

71

break;

72

73

cout << "Hobby: ";

74

cin.getline(pa[i].hobby,SLEN);

75

cout << "OOP Level: ";

76

(cin >> pa[i].ooplevel).get();

77

78

return i;

79 }
80
81 void display1(student st)
82 {
83

cout << "\n\n============= Display1 (student st)======";

84

cout << "\nStudent's name: " << st.fullname;

85

cout << "\nHobby: " << st.hobby;

86

cout << "\nOOP Level: " << st.ooplevel;

87

cout << "\n============= END OF Display1 (student st)======" << endl;

88 }
89
90 void display2(const student * ps)

91 {
92

cout << "\n\n--------------- Display2 (const student * ps)----";

93

cout << "\n&Student's name: " << ps->fullname;

94

cout << "\n&Hobby: " << ps->hobby;

95

cout << "\n&OOP Level: " << ps->ooplevel << endl;

96

cout << "\n--------------- END OF Display2 (const student * ps)----";

97
98 }
99
100void display3(const student pa[], int n)
101{
102 if (n == 0)
103

return;

104 cout << "\n\n========= Display3 ========";


105 for (int i=0; i < n; i++)
106 {
107
108

cout << "\nStudent #" << i+1 << ": ";

109

cout << "\nFullname: " << pa[i].fullname;

110

cout << "\nHobby: " << pa[i].hobby;

111

cout << "\nOOP Level: " << pa[i].ooplevel;

112

cout << "\n------------";

113 }
114 cout << "\n\n========= END OF Display3 ========";
115}

2 Responses to C++ Primer Plus Chapter 7 Exercise 8 Answer


1. Pingback: C++ Primer Plus78 | -CloverStd
2.

Saad says:
February 12, 2012 at 3:11 pm

// C++ Primer Plus Exercise


// Chapter 7, Exercise 8
#include
const int SLEN = 30;
struct student
{
char fullname[SLEN];
char hobby[SLEN];
int ooplevel;
};
int getinfo(student pa[], int n);
void display1(student st);
void display2(const student * ps);
void display3(const student pa[], int n);
int main()
{
using namespace std;
cout <> class_size;
while (cin.get() != \n)
continue;
student * ptr_stu = new student[class_size];
int entered = getinfo(ptr_stu, class_size);
for (int i = 0; i < entered; i++)
{
display1(ptr_stu[i]);
display2(&ptr_stu[i]);
}
display3(ptr_stu, entered);
delete [] ptr_stu;
cout << "Done\n";
return 0;
}
// getinfo() has two arguments: a pointer to the first element of
// an array of student structures and an int representing the
// number of elements of the array. The function solicits and

// stores data about students. It terminates input upon filling


// the array or upon encountering a blank line for the student
// name. The function returns the actual number of array elements
// filled.
int getinfo(student pa[], int n)
{
std::cout << "Populating student database"
"\nEnter blank line to terminate.\n";
student *temp = new student;
temp = pa;
int i=0;
for(;pa < (temp+n); pa++)
{
std::cout << "Entry #" << i+1 << std::endl;
std::cout <fullname, SLEN);
if(pa->fullname[0] == )
break;
std::cout <hobby, SLEN);
std::cout <> pa->ooplevel;
std::cin.get();
i++;
}
std::cout << "Populated\n";
delete temp;
return i;
}
// display1() takes a student structure as an argument
// and displays its contents
void display1(student st)
{
std::cout << "========= .: Display 1 :. =========\n";
std::cout << "Name: " << st.fullname << "\n";
std::cout << "Hobby: " << st.hobby << "\n";
std::cout << "OOP Level: " << st.ooplevel << "\n";
std::cout << "=====================================\n";
}
// display2() takes the address of student structure as an
// argument and displays the structures contents
void display2(const student * ps)
{
std::cout << "========= .: Display 2 :. =========\n";
std::cout << "Name: " <fullname << "\n";

std::cout << "Hobby: " <hobby << "\n";


std::cout << "OOP Level: " <ooplevel << "\n";
std::cout << "=====================================\n";
}
// display3() takes the address of the first element of an array
// of student structures and the number of array elements as
// arguments and displays the contents of the structures
void display3(const student pa[], int n)
{
const student *temp = new student;
temp = pa;
std::cout << "========= .: Display 3 :. =========\n";
for(; pa < (temp+n); pa++)
{
std::cout << "Name: " <fullname << "\n";
std::cout << "Hobby: " <hobby << "\n";
std::cout << "OOP Level: " <ooplevel << "\n";
}
std::cout << "=====================================\n";
delete temp;
}

8. Design a function calculate() that takes two type double values and a pointer to a
function that takes two double arguments and returns a double. The calculate() function
should also be type double, and it should return the value that the pointed-to function
calculates, using the double arguments to calculate(). For example, suppose you
have this definition for the add() function:
double add(double x, double y)
{
return x + y;
}
Then, the function call in
double q = calculate(2.5, 10.4, add);
would cause calculate() to pass the values 2.5 and 10.4 to the add() function and
then return the add() return value (12.9).
Use these functions and at least one additional function in the add() mold in a program.
The program should use a loop that allows the user to enter pairs of numbers. For each
pair, use calculate() to invoke add() and at least one other function. If you are feeling
adventurous, try creating an array of pointers to add()-style functions and use a loop to
successively apply calculate() to a series of functions by using these pointers. Hint:
Heres how to declare such an array of three pointers:
double (*pf[3])(double, double);

You can initialize such an array by using the usual array initialization syntax and function
names as addresses.
My Answer:
1 #include <iostream>
2
3 double shifr1(double x, double y);
4 double shifr2(double x, double y);
5 double shifr3(double x, double y);
6 double calculate (double x, double y, double (*pf[3])(double, double));
7
8 int main()
9 {
10
11using namespace std;
12
13double (*pf[3])(double,double) = {shifr2,shifr1,shifr3};
14int x,y = 0;
15
16cout << "Enter two pairs of numbers (-1) to exit: ";
17
18while (cin >> x >> y)
19{
20 if (x == -1 || y == -1)
21

break;

22 cout << "\nCalculate is " << calculate(x,y,pf) << endl;


23}
24
25cout << "\nBye!";
26cin.get();
27cin.get();
28return 0;

29}
30
31double shifr1(double x, double y)
32{
33 double shifr = 0;
34
35 shifr = x + y;
36
37 return shifr;
38}
39
40double shifr2(double x, double y)
41{
42 double shifr = 0;
43
44 shifr = x * y;
45
46 return shifr;
47}
48
49double shifr3(double x, double y)
50{
51 double shifr = 0;
52
53 shifr = x - y;
54
55 return shifr;
56}
57
58double calculate (double x, double y, double (*pf[3])(double x2, double y2))
59{

60 double calc = 0;
61
62 for (int i=0; i < 3; i++)
63 {
64

calc = calc + pf[i](x,y);

65 }
66
67 return calc;
68}

One Response to C++ Primer Plus Chapter 7 Exercise 9 Answer

1.

Saad says:
February 12, 2012 at 7:30 pm
// C++ Primer Plus Exercise
// Chapter 7, Exercise 9
#include
//- Function(s) Prototype(s)
double calculate(double, double, double (*[])(double, double));
double add(double, double);
double subt(double, double);
double mult(double, double);
double div(double, double);
int main()
{
using namespace std;
double (*pfunct[4])(double, double) = {add, subt, mult, div};
// double (*npfunt)(double, double) = new double[4]; TODO:: Figure out how to
create a dynamic array of pointer-to-function
double x, y;
cout <> x >> y)
{
calculate(x, y, pfunct);

cout << "\nPlease enter two numbers to perform calculations on (no numeric to quit):
";
}
cout << "\nAdios!";
return 0;
}
//- Function(s)
double calculate(double x, double y, double (*funct[])(double, double))
{
for(int i=0; i<4; i++)
{
switch (i+1)
{
case 1: std::cout << "\nAdd Function: ";
break;
case 2: std::cout << "\nSubtract Function: ";
break;
case 3: std::cout << "\nMultiply Function: ";
break;
case 4: std::cout << "\nDivide Function: ";
break;
}
std::cout << (*(funct+i))(x,y);
}
return 0;
}
double add(double x, double y)
{
return x+y;
}
double subt(double x, double y)
{
return x-y;
}
double mult(double x, double y)
{
return x*y;
}
double div(double x, double y)
{
return x/y;

}
//

Вам также может понравиться