java answers

35
Appendix I Answers to Odd Numbered Exercises Chapter 1 1. a. true; b. false; c. false; d. false; e. true; f; false; g. false; h. true; i. true; j. true 3. Fetch and decode instructions, control the flow of information (instructions or data) in and out of main memory, and control the operation of the internal components of the CPU. 5. Screen and printer. 7. Every computer directly understands its own machine language. Therefore, for the computer to execute a program written in a high- level language, the high-level language program must be translated into the computer’s machine language. 9. A well-analyzed problem leads to a well-designed algorithm. Moreover, a program that is well analyzed is easier to modify as well as spot and fix errors. 11. To find the weighted average of the four test scores, first you need to know each test score and its weight. Next, you multiply each test score with its weight, and then add these numbers; the sum is then divided by four to get the average. Therefore, 1. Get testScore1, weightTestScore1 2. Get testScore2, weightTestScore2 3. Get testScore3, weightTestScore3 4. Get testScore4, weightTestScore4

Upload: el-lobo-proscrito

Post on 20-Jul-2016

43 views

Category:

Documents


1 download

DESCRIPTION

Answers to chapter 1 - 19 questions

TRANSCRIPT

Appendix I

Answers to Odd Numbered ExercisesChapter 1

1. a. true; b. false; c. false; d. false; e. true; f; false; g. false; h. true; i. true; j. true

3. Fetch and decode instructions, control the flow of information (instructions or data) in and out of main memory, and control the operation of the internal components of the CPU.

5. Screen and printer.

7. Every computer directly understands its own machine language. Therefore, for the computer to execute a program written in a high-level language, the high-level language program must be translated into the computer’s machine language.

9. A well-analyzed problem leads to a well-designed algorithm. Moreover, a program that is well analyzed is easier to modify as well as spot and fix errors.

11. To find the weighted average of the four test scores, first you need to know each test score and its weight. Next, you multiply each test score with its weight, and then add these numbers; the sum is then divided by four to get the average. Therefore,

1. Get testScore1, weightTestScore1

2. Get testScore2, weightTestScore2

3. Get testScore3, weightTestScore3

4. Get testScore4, weightTestScore4

5. sum = testScore1 * weightTestScore1 +

testScore2 * weightTestScore2 +

testScore3 * weightTestScore3 +

testScore4 * weightTestScore4;

6. average = sum / 4;

13. To calculate the selling price of an item, we need to know the original price (the price the store pays to buy) of the item. We can then the use the following formula to find the selling price:

sellingPrice = originalPrice + originalPrice * .60

The algorithm is as follows:

a. Get originalPrice

b. Calculate the sellingPrice using the formula:

sellingPrice = originalPrice + originalPrice * .60

The information needed to calculate the selling price is the original price and the marked-up percentage.

15. Let r denote the radius of the circle. Given the lengths a, b, and c, such that a + b + c is the circumference of the circle, we have 2πr = a + b + c. This implies that r = (a + b + c) / (2π). We can now write the algorithm as follows:

a. Get the values of a, b, c

b. Calculate r using the formula: r = (a + b + c) / (2π)

17. Suppose averageTestScore denotes the average test score, highestScore denotes the highest test score, testScore denotes a test score, sum denote the sum of all the test scores, and count denotes the number of students in class, and studentName denotes the name of a student.

a. First you design an algorithm to find the average test score. To find the average test score, first you need to count the number of students in the class and add the test score of each student. You then divide the sum by count to find the average test score. The algorithm to find the average test score is as follows:

i. Set sum and count to 0.

ii. Repeat the following for each student in class.

1. Get testScore

2. Increment count and update the value of sum by adding the current test score to sum.

iii. Use the following formula to find the average test score.

if (count is 0)

averageTestScore = 0;

otherwise

averageTestScore = sum / count;

b. The following algorithm determines and prints the names of all the students whose test score is below the average test score.

Repeat the following for each student in class:

i. Get studentName and testScore

ii.

if (testScore is less than averageTestScore)

print studentName

c. The following algorithm determines and highest test score

i. Get first student’s test score and call it highestTestScore.

ii. Repeat the following for each of the remaining student in class

1. Get testScore

2.

if (testScore is greater than highestTestScore)

highestTestScore = testScore;

d. To print the names of all the students whose test score is the same as the highest test score, compare the test score of each student with the highest test score and if they are equal print the name. The following algorithm accomplishes this

Repeat the following for each student in class:

i. Get studentName and testScore

ii.

if (testScore is equal to highestTestScore)

print studentName

You can use the solutions of the subproblems obtained in parts a to d to design the main algorithm as follows:

1. Use the algorithm in part a to find the average test score.

2. Use the algorithm in part b to print the names of all the students whose score is below the average test score.

3. Use the algorithm in part c to find the highest test score.

4. Use the algorithm in part d to print the names of all the students whose test score is the same as the highest test score

Chapter 2

1. a. false; b. false; c. false; d. true; e. true; f. false; g. true; h. true; i. false; j. true; k. false

3. a, b

5. a. 3

b. Not possible. Both the operands of the operator % must be integers. Because the second operand, w, is a floating-point value, the expression is invalid.

c. Not possible. Both the operands of the operator % must be integers. Because the first operand, which is y + w, is a floating-point value, the expression is invalid .

d. 38.5

e. 1

f. 2

g. 2

h. 420.0

7. 7

9. a and c are valid

11. a. –10 * a

b. '8'

c. (b * b – 4 * a * c) / (2 * a)

d. (–b + (b * b – 4 * a * c)) / (2 * a)

13. x = 20

y = 15

z = 6

w = 11.5

t = 4.5

15. a. 0.50

b. 24.50

c. 37.6

d. 8.3

e. 10

f. 38.75

17. a and c are correct

19. a. x *= 2;

b. x += y - 2;

c. sum += num;

d. z *= x + 2;

e. y /= x + 5;

21.

a b c

a = (b++) + 3; 9 7 und

c = 2 * a + (++b); 9 8 26

b = 2 * (++c) – (a++); 10 45 27

23. (The user input is shaded.)

a = 25Enter two integers : 20 15

The numbers you entered are 20 and 15z = 45.5Your grade is AThe value of a = 65

25.

#include <iostream> #include <string>

using namespace std;

const double X = 13.45;const int Y = 34;const char BLANK = ' ';

int main() { string firstName, lastName; int num; double salary;

cout << "Enter first name: "; cin >> firstName; cout << endl;

cout << "Enter last name: "; cin >> lastName; cout << endl;

cout << "Enter a positive integer less than 70: "; cin >> num; cout << endl; salary = num * X; cout << "Name: " << firstName << BLANK << lastName << endl; cout << "Wages: $" << salary << endl; cout << "X = " << X << endl; cout << "X + Y = " << X + Y << endl; return 0; }

Chapter 3

1. a. true; b. true; c. false; d. false; e. true; f. true

3. a. x = 37, y = 86, z = 0.56

b. x = 37, y = 32, z = 86.56

c. Input failure: z = 37.0, x = 86, trying to read the . (period) into y.

5. Input failure: Trying to read A into y, which is an int variable. x = 46, y = 18, and z = 'A'. The values of y and z are unchanged.

7. a. name = " Mickey Balto", age = 35

b. name = " ", age = 35

9.#include <iostream>#include <fstream>

using namespace std;

int main(){ int num1, num2; ifstream infile; ostream outfile;

infile.open("input.dat"); outfile.open("output.dat");

infile >> num1 >> num2; outfile << "Sum = " << num1 + num2 << endl;

infile.close(); outfile.close();

return 0;}

11. a. Same as before.

b. The file contains the output produced by the program.

c. The file contains the output produced by the program. The old contents are erased.

d. The program would prepare the file and store the output in the file.

Chapter 4

1. a. false; b. false; c. false; d. true; e. false; f. false; g. false; h. false; i. false; j. true

3. 100 200 0

5. Omit the semicolon after else. The correct statement is:

if (score >= 60) cout << "You pass." << endl;else cout << "You fail." << endl;

7. 15

9. 96

11.#include <iostream>

using namespace std;const int one = 5;

int main(){ int x, y, w, z;

z = 9;

if (z > 10) { x = 12; y = 5; w = x + y + one; } else { x = 12; y = 4; w = x + y + one; }

cout << "w = " << w << endl;

return 0;}

Chapter 5

1. false; b. true; c. false; d. true; e. true; f. true; g. true; h. false

3. 5

5. if ch > 'Z' or ch < 'A'

7. Sum = 158

9. Sum = 158

11. 11 18 25

13. a. 18

b. 14

c. false

15. 2 7 17 37 77 157

17. a. *

b. infinite loop

c. infinite loop

d. ****

e. ******

f. ***

19. WHAT IS DONE , OFTEN IS NOT DONE WELL.

21.

0 - 2425 - 4950 - 7475 - 99100 - 124125 - 149150 - 174175 - 200

23. a. both

b. do...while

c. while

d. while

25. There is more than one answer to this problem. One solution is:

do{ cin >> number; if (number != -1) total = total + number; count++;}while (number != -1);

27. a. number = 1;while (number <= 10){ cout << setw(3) << number; number++;}

b.number = 1;do{ cout << setw(3) << number; number++;} while (number <= 10);

29. 11 18 25

Chapter 6

1. a. false; b. true; c. true; d. true; e. false

3. a, b, c, e, f, and g are valid. In d, the function call in the output (cout) statement requires one more argument.

5. a. 4; int

b. 2; double

c. 4; char

d. The function test requires four actual parameters. The order of the parameters is: int, char, double, int.

e. cout << test(5, 'z', 7.3, 5) << endl;

f. cout << two(17.5, 18.3) << endl;

g. cout << static_cast<char>(static_cast<int>(three(4, 3, 'A', 17.6)) + 1)

<< endl;

7. a. (i) 125 (ii) 432

b. The function computes x3, where x is the argument of the function.

9. 12624120

Chapter 7

1. a. true; b. false; c. true; d. false; e. true; f. false; g. false; h. false; i. true

3. a. A variable declared in the heading of a function definition is called a formal parameter. A variable or expression used in a function call is called an actual parameter.

b. A value parameter receives a copy of the actual parameter’s data. A reference parameter receives the address of the actual parameter.

c. A variable declared within a function or block is called a local variable. A variable declared outside of every function definition is called a global variable.

5.3 4 20 787 3 20 47 5 6 2

7.

#include <iostream>

using namespace std;

void func(int val1, int val2);

int main() { int num1, num2;__1__ cout << "Please enter two integers." << endl;__2__ cin >> num1 >> num2;__3__ func (num1, num2);__7__ cout << " The two integers are " << num1 << ", " << num2 << endl;__8__ return 0; }

void func (int val1, int val2) { int val3, val4;__4__ val3 = val1 + val2;__5__ val4 = val1 * val2;__6__ cout << "The sum and product are " << val3 << " and " << val4 << endl; }

9.

Line 4: In main: num1 = 10, num2 = 20, and t = 15Line 9: In funOne: a = 15, x = 10, z = 25, and t = 15Line 11: In funOne: a = 15, x = 15, z = 25, and t = 15Line 13: In funOne: a = 27, x = 15, z = 25, and t = 27Line 15: In funOne: a = 40, x = 15, z = 25, and t = 40Line 6: In main after funOne: num1 = 15, num2 = 20, and t = 40

11. (i), (ii), and (iv) are correct.

Chapter 8

1. a. true; b. false; c. true; d. false; e. false; f. true; g. true; h. true; i. false; j. true; k. false

3. Only a and c are valid.

5. The statement:

using namespace std;

is missing between Lines 1 and 2.

7. Either include the statement:

using namespace aaa;

before the function main or refer to the identifiers x and y in main as aaa::x and aaa::y, respectively.

9.

Going to the Amusement Park1410musemABCDEFGHIJK11aBdDEFGHIJK

Chapter 9

1. a. true; b. true; c. false; d. false; e. true; f. false; g. false; h. false; i. true; j. false; k. false; l. false

3.

a. funcOne(list, 50);

b. cout << funcSum(50, list[3]) << endl;

c. cout << funcSum(list[29], list[9]) << endl;

d. funcTwo(list, Alist);

5. list elements are: 5, 6, 9, 19, 23, 37

7. a. Invalid; the assignment operator is not defined for C-strings.

b. Invalid; the relational operators are not defined for C-strings.

c. Invalid; the assignment operator is not defined for C-strings.

d. Valid

9.

a. strcpy(str1, "Sunny Day");

b. length = strlen(str1);

c. strcpy(str2, name);

d.

if (strcmp(str1, str2) <= 0) cout << str1 << endl;else cout << str2 << endl;

11. List elements: 11 16 21 26 30

13. a. 30

b. 5

c. 6

d. row

e. column

15. a. beta is initialized to 0.

b.

First row of beta: 0 1 2Second row of beta: 1 2 3Third row of beta: 2 3 4

c. First row of beta: 0 0 0Second row of beta: 0 1 2Third row of beta: 0 2 4

d. First row of beta: 0 2 0Second row of beta: 2 0 2Third row of beta: 0 2 0

Chapter 10

1. a. false; b. true; c. false; d. false; e. false

3. a. 5

b. 7

c. 8

d. 11

5. List before the first iteration: 26, 45, 17, 65, 33, 55, 12, 18

List after the first iteration: 26, 17, 45, 33, 55, 12, 18, 65

List after the second iteration: 17, 26, 33, 45, 12, 18, 55, 65

List after the third iteration: 17, 26, 33, 12, 18, 45, 55, 65

List after the fourth iteration: 17, 26, 12, 18, 33, 45, 55, 65

List after the fifth iteration: 17, 12, 18, 26, 33, 45, 55, 65

List after the sixth iteration: 12, 17, 18, 26, 33, 45, 55, 65

List after the seventh iteration: 12, 17, 18, 26, 33, 45, 55, 65

7. 3

9. 10, 12, 18, 21, 25, 28, 30, 71, 32, 58, 15

11. To use a vector object in a program, the program must include the header file vector.

13. 1 3 5 7 9

15.

a. vector<int> secretList;b.secretList.push_back(56);secretList.push_back(28);secretList.push_back(32);secretList.push_back(96);secretList.push_back(75);

c.for (unsigned int i = 0; i < secretList.size(); i++) cout << secretList[i] << " ";

cout << endl;

17. a. cout << myList.front() << " " << myList.back() << endl;

b length = myList.size();

c.for (int i = 0; i < myList.size(); i++) cout << myList[i] << " ";

cout << endl;

Chapter 11

1. a. false; b. false; c. true; d. true; e. true; f. true; g. false

3. a. Invalid; the member name of newEmployee is a struct. Specify the member names to store the value "John Smith". For example,

newEmployee.name.first = "John";newEmployee.name.last = "Smith";

b. Invalid; the member name of newEmployee is a struct. There are no aggregate output operations on a struct. A correct statement is:

cout << newEmployee.name.first << " " << newEmployee.name.last << endl;

c. Valid

d. Valid

e. Invalid; employees is an array. There are no aggregate assignment operations on arrays.

Chapter 12

1. a. false; b. false; c. true; d. false; e. false;

3. a. 6

b. 2

c. 2

d.

void xClass::func(){ u = 10; w = 15.3;}

e. void xClass::print(){ cout << u << " " << w << endl;}

f. xClass::xClass(){ u = 0; w = 0;}

g. x.print();

h. xClass t(20, 35.0);

5. a. int testClass::sum(){ return x + y;}

void testClass::print() const{ cout << "x = " << x << ", y = " << y << endl;}

testClass::testClass(){ x = 0; y = 0;}

testClass::testClass(int a, int b){ x = a; y = b;}

b. One possible solution. (We assume that the name of the header file containing the definition of the class testClass is Exercise5Ch12.h.)

#include <iostream.h>#include "Exercise5Ch12.h"

int main(){ testClass one; testClass two(4, 5);

one.print(); two.print();

return 0;}

7. a. personType student("Buddy", "Arora");

b. student.print();

c. student.setName("Susan", "Gilbert");

9. a. myClass::count = 0;

b. myClass.incrementCount();c. myClass.printCount();d.

int myClass::count = 0;

void myClass::setX(int a){ x = a;}

void myClass::printX() const{ cout << x;}

void myClass::printCount(){ cout << count;}

void myClass::incrementCount(){ count++;}

myClass::myClass(int a){ x = a;}

e. myClass myObject1(5);f. myClass myObject2(3);

g. The statements in Lines 1 and 2 are valid.

The statement in Line 3 should be: myClass::printCount();.

The statement in Line 4 is invalid because the member function printX is not a static member of the class, and so cannot be called by using the name of class.

The statement in Line 5 is invalid because count is a private static member variable of the class.

h. 52231433

Chapter 13

1. a. true; b. true; c. true

3. Some of the member variables that can be added to the class employeeType are: department, salary, employeeCategory (such as supervisor and president), and employeeID. Some of the member functions are: setInfo, getSalary, getEmployeeCategory, and setSalary.

5. a. The statement :

class bClass public aClass

should be:

class bClass: public aClass

b. Missing semicolon after }.

7.a.yClass::yClass(){ a = 0; b = 0;}

b.xClass::xClass(){ z = 0;}

c.void yClass::two(int u, int v){ a = u; b = v;}

9. a.

void two::setData(int a, int b, int c){ one::setData(a, b); z = c;}

b.void two::print() const{ one::print(); cout << z << endl;}

11.In base: x = 7In derived: x = 3, y = 8; x + y = 11****7####11

Chapter 14

1. a. false; b. false; c. false; d. true; e. true; f. true; g false; h. false

3.

98 9898 98

5. b and c

7. 78 78

9. 4 4 5 7 10 14 19 25 32 40

11. In a shallow copy of data, two or more pointers point to the same memory space. In a deep copy of data, each pointer has its own copy of the data.

13.

Array p: 5 7 11 17 25Array q: 25 17 11 7 5

15. The copy constructor makes a copy of the actual variable.

17. Classes with pointer data members should include the destructor, overload the assignment operator, and explicitly provide the copy constructor by including it in the class definition and providing its definition.

19.ClassA x: 4

ClassA x: 6ClassB y: 10

21. Yes.

23.a. Because employeeType is an abstract class, you cannot instantiate an object of this class.

Therefore, this statement is illegal.b. This statement is legal.c. This statement is legal.

Chapter 15 

1. a. false; b. true; c. true; d. false; e. false; f. true; g. false; h. true; i. false; j. true; k. false

3. Because the left operand of << is a stream object, which is not of the type mystery.

5. When the class has pointer data members.

7. a. friend strange operator+(const strange&, const strange&);

b. friend bool operator==(const strange&, const strange&);

c. friend strange operator++(strange&, int);

9. In Line 2, the word friend before the word bool is missing. The correct statement is:

friend bool operator<=(mystery, mystery); //Line 2

11. None.

13. One.

15.

class complexType{ //overload the stream insertion and extraction operators friend ostream& operator<<(ostream&, const complexType&); friend istream& operator>>(istream&, complexType&);

public: void setComplex(const double& real, const double& imag); //set the complex number according to the parameters //Postcondition: realPart = real; imaginaryPart = imag

complexType(double real = 0, double imag = 0); //constructor //initialize the complex number according to the parameters //Postcondition: realPart = real; imaginaryPart = imag

complexType operator+(const complexType& otherComplex) const; //overload + complexType operator*(const complexType& otherComplex) const; //overload *

complexType operator~() const;

double operator!() const;

bool operator==(const complexType& otherComplex) const; //overload ==

private: double realPart; //variable to store the real part double imaginaryPart; //variable to store the imaginary part};

// Definitions of operator~ and operator!complexType complexType::operator~() const

{ complexType temp = *this;

temp.imaginaryPart = -temp.imaginaryPart;

return temp;}

double complexType::operator!() const{ return (pow((realPart * realPart + imaginaryPart * imaginaryPart), 0.5));}

17. Error in Line 4. A template instantiation can be for only a built-in type or a user-defined type. The word “type” between the angular brackets must be replaced either with a built-in type or a user-defined type.

19. a. 12 b. Sunny Day

21.

template <class Type>void swap(Type &x, Type &y){ Type temp; temp = x; x = y; y = temp;}

Chapter 16

1. a. false, b. true, c. true, d. false

3. a. Entering the try block.Exception: Lower limit violation.After the catch block

b.Entering the try block.Exception: 0After the catch block

c. Entering the try block.Exiting the try block.After the catch block

d.Entering the try block.Exception: 0After the catch block

5. (Assume that the definition of the class tornadoException is in the header file tornadoException.h.)

#include <iostream>#include "tornadoException.h"

using namespace std;

int main(){ int miles;

try { cout << "Enter the miles: "; cin >> miles; cout << endl;

if (miles < 5) throw tornadoException(); else throw tornadoException(miles); } catch (tornadoException tE) { cout << tE.what() << endl; }

return 0;}

Chapter 17

1. a. true; b. true; c. false; d. false; e. false

3. The case in which the solution is defined in terms of smaller versions of itself.

5. A function that calls another function and eventually results in the original function call is said to be indirectly recursive.

7. a. The statements in Lines 2 and 3.

b. The statements in Lines 4 and 5.

c. Any nonnegative integer.

d. It is a valid call. The value of mystery(0) is 0.

e. It is a valid call. The value of mystery(5) is 15.

f. It is an invalid call. It will result in infinite recursion.

9. a. It does not produce any output.

b. 5 6 7 8 9

c. It does not produce any output.

d. It does not produce any output.

11. a. 2

b. 3

c. 5

d. 21

13.

The base cases are when n = 0 or n = 1. The general case is specified by the option otherwise.

Chapter 18

1. a. false; b. false; c. false; d. false

3. a. true

b. true

c. false

d. false

e. true

5. a. A = A->link;

b. list = A->link->link;

c. B = B->link->link;

d. list = NULL;

e. B->link->info = 35;

f. newNode = new nodeType;

newNode->info = 10;

newNode->link = A->link;

A->link = newNode;

g. p = A->link;

A->link = p->link;

delete p;

7. a. This is an invalid code. The statement s->info = B; is invalid because B is a pointer and s->info is an int.

b. This is an invalid code. After the statement s = s->link; executes, s is NULL and so s->info does not exist.

9. Item to be deleted is not in the list.18 38 2 15 45 25

11.

13.

Chapter 19

1. x = 3y = 9713 4 7

3. a. 26

b. 45

c. 8

d. 29

5. a. A * B + Cb. (A + B) * (C – D)c. (A – B – C) * D

7. 10 20 30 40 50

9. template <class elemType>elemType second(stackType<elemType> stack){ elemType temp1, temp2;

if (stack.isEmptyStack()) { cout << "Stack is empty." << endl; exit(0); //terminate the program }

temp1 = stack.top(); stack.pop();

if (stack.isEmptyStack()) { cout << "Stack has only one element." << endl; exit(0); //terminate the program } temp2 = stack.top(); stack.push(temp1);

return temp2;}

11. Queue Element = 0Queue Element = 14Queue Element = 22Sorry, the queue is emptySorry, the queue is emptyStack Element = 32Stack Elements: 64 28 0

Queue Elements: 30

13. a. queueFront = 50; queueRear = 0.b. queueFront = 51; queueRear = 99.

15. a. queueFront = 25; queueRear = 76.b. queueFront = 26; queueRear = 75.

17. 51

19. template <class Type>void reverseStack(stackType<Type> &s){ linkedQueueType<Type> q; Type elem;

while (!s.isEmptyStack()) { elem = s.top(); s.pop(); q.addQueue(elem); }

while (!q.isEmptyQueue()) { elem = q.front(); q.deleteQueue(); s.push(elem); }}

21. template <class Type>int queueType<Type>::queueCount(){ return count;}

23.

25.