ebook img

Answers to Selected Exercises for Programming and Problem Solving With C++ PDF

154 Pages·2004·0.649 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Answers to Selected Exercises for Programming and Problem Solving With C++

DalePhatANS_complete 8/18/04 10:30 AM Page 1049 Answers to Selected Exercises Chapter 1 Exam Preparation Exercises 1. a.v, b.i, c.viii, d.iii, e.iv, f.vii, g.vi, h.ii. 2. Analysis and specification, general solution (algorithm), verify. 3. Concrete solution (program), test. 4. The analysis and specification step within the problem-solving phase. 5. The steps never end. Changing the last step to say, “Repeat from first step until gradua- tion,” converts the sequence into an algorithm that eventually ends, assuming the person will graduate from school some day. We can make sure that this loop ends by specifying a condition that will definitely occur. For example, “Repeat from first step until last day of classes.” 6. a.vi, b.ii, c. v, d.i, e.vii, f.iv. 7. The program can be compiled on different computer systems without modification. 8. The control unit directs the actions of the other components in the computer to execute program instruction in the proper order. 9. False. The editor is software rather than hardware. 10. False. Peripheral devices are external to the CPU and its main memory. 11. Yes. If the software license restricts use to a single computer or a single user, then this is a case of piracy, even though you split the cost. 12. a.ii, b.v, c. iii, d.vii, e.i, f.vi, g.iv. Chapter 1 Programming Warm-Up Exercises 1. Branches: Steps n1, n2, and n3. There are two loops: steps p, q, and r; and steps t and u. Steps a, c, and e are references to subalgorithms defined elsewhere. DalePhatANS_complete 8/18/04 10:30 AM Page 1050 1050 | Answers to Selected Exercises 2. follow separate algorithm for filling glass with water and placing on counter If right-handed, pick up toothpaste tube in left hand and unscrew cap by turning counter-clockwise place toothpaste cap on counter transfer toothpaste tube to right hand and pick up toothbrush in left hand, holding it by its handle place open end of toothpaste tube against tips of brush bristles and squeeze toothpaste tube just enough to create a 0.5-inch-long extrusion of toothpaste on brush pull toothpaste tube away from brush and place tube on counter transfer toothbrush to right hand, holding it by its handle open mouth and insert brush, placing toothpaste-covered bristles against one tooth scrub tooth with brush by moving brush up and down 10 times reposition brush to an unscrubbed tooth repeat previous two steps until all teeth have been brushed spit toothpaste into sink put toothbrush in sink pick up glass in right hand fill mouth with water from glass swish water in mouth for five seconds spit water from mouth into sink repeat previous three steps three times Otherwise (if left-handed) pick up toothpaste tube in right hand and unscrew cap by turning counter-clockwise place toothpaste cap on counter transfer toothpaste tube to left hand and pick up toothbrush in right hand, holding it by its handle place open end of toothpaste tube against tips of brush bristles and squeeze toothpaste tube just enough to create a 0.5-inch-long extrusion of toothpaste on brush pull toothpaste tube away from brush and place tube on counter transfer toothbrush to left hand, holding it by its handle open mouth and insert brush, placing toothpaste-covered bristles against one tooth scrub tooth with brush by moving brush up and down 10 times reposition brush to an unscrubbed tooth repeat previous two steps until all teeth have been brushed spit toothpaste into sink put toothbrush in sink pick up glass in left hand fill mouth with water from glass swish water in mouth for five seconds spit water from mouth into sink repeat previous three steps three times Place glass on counter Follow separate algorithm for cleaning up after brushing teeth DalePhatANS_complete 8/18/04 10:30 AM Page 1051 Answers to Selected Exercises | 1051 3. The test for right- or left-handedness is a branch. Each branch contains two loops, one that iterates until all teeth are brushed and another that iterates rinsing four times. The first and last steps refer to separately defined subalgorithms. 4. Change step u to: u. Repeat step t nine times. Chapter 1 Case Study Follow-Up Exercises 1. a. 1900 No b. 2000 Yes c. 1996 Yes d. 1998 No 2. a. 1900 Line = 6 b. 1945 Line = 2 c. 1600 Line = 7 d. 1492 Line = 4 e. 1776 Line = 4 3. Divide by 1000 and see if the remainder is 0. 4. I was not, but your answer may be different. 5. Keep adding 1 to the year and test it until you find the next leap year. Another algo- rithm would be to use the following: nextYear = year + (year % 4) divide the nextYear by 100 and if the remainder isn’t 0, Write that nextYear is the next leap year Otherwise, divide the nextYear by 400 and if the remainder isn’t 0 Write that (nextYear + 4) is the next leap year Otherwise nextYear is the next leap year 6. Line Number { __1___ if (year % 4 != 0) __2___ return false; __3___ else if (year % 100 != 0) __4___ return true; __5___ else if (year % 400 != 0) __6___ return false; __7___ else return true; } Chapter 2 Exam Preparation Exercises 1. a. valid, b. invalid (hyphens not allowed), c. invalid (reserved words not allowed), d.valid, e.valid, f.valid, g.invalid (must begin with a letter), h. invalid (# is not allowed). 2. a.vi, b.ix, c.iv, d.v, e.vii,f. ii, g.i, h.x, i.iii, j.viii. 3. False. DalePhatANS_complete 8/18/04 10:30 AM Page 1052 1052 | Answers to Selected Exercises 4. The template allows an identifier to begin with a digit. Identifiers can begin with a letter or an underscore, and digits may appear only in the second character position and beyond. 5. False. 6. True. 7. True. 8. Note that the second line concatenates two words without a separating space. Four score and seven years agoour fathers brought forth on this continent a new nation... 9. ”Bjarne Stroustrup named his new programming language C++ because it is a successor to the C programming language.” 10. By preceding it with a backslash character (\”). 11. If we forget the */ at the end of a comment, then any number of lines of program code can be inadvertently included in the comment. The // form avoids this by automatically terminating at the end of the line. 12. The // form of comment cannot span more than one line. It also cannot be inserted into the middle of a line of code because everything to the right of //becomes a comment. 13. <<is the stream insertion operator, and is pronounced “put to” or “is sent,” as in “cout is sent string4.” 14. No. The endlidentifier is a manipulator, and is not a string value. 15. It tells the C++ preprocessor to insert the contents of a specified file at that point in the code. 16. std::cout << "Hello everybody!" << std::endl; 17. A block. 18. By splitting it into pieces that fit on a line, and joining them with the concatenation operator. 19. #include <iostream> #include <string> using namespace std; const string TITLE = "Dr."; int main() { cout << "Hello " + TITLE + " Stroustrup!"; } Chapter 2 Programming Warm-Up Exercises 1. Substitute the actual data in the following: cout << "July 4, 2004" << endl; DalePhatANS_complete 8/18/04 10:30 AM Page 1053 Answers to Selected Exercises | 1053 2. Note that the \"escape sequence is needed in six places here: cout << "He said, \"How is that possible?\"" << endl << "She replied, \"Using manipulators.\"" << endl << "\"Of course,\" he exclaimed!" << endl; 3. a. const string ANSWER = "True"; b. char middleInitial; c. string courseTitle; d. const char PERCENT = '%' 4. const string FIRST = "Your first name inserted here"; const string LAST = "Your last name inserted here"; // Insert your middle initial in place of A: const char MIDDLE = 'A'; 5. cout << PART1 << PART2 << PART1 << PART3; 6. PART1 + PART2 + PART1 + PART3 7. cout << "Yet the web of thought has no such creases" << endl; cout << "And is more like a weaver's masterpieces;" << endl; cout << "One step a thousand threads arise," << endl; cout << "Hither and thither shoots each shuttle," << endl; cout << "The threads flow on unseen and subtle," << endl; cout << "Each blow effects a thousand ties." << endl; 8. #include <iostream> #include <string> using namespace std; const string TITLE = "Rev."; const char FIRST = 'H'; const char MID 'G'; const char DOT = '.'; int main() { cout << TITLE << FIRST << DOT << MID << DOT << " Jones"; } 9. The solution to this problem is for the student to show that he or she has run the pro- gram correctly. It should output: *********************************** * * * Welcome to C++ Programming! * * * *********************************** DalePhatANS_complete 8/18/04 10:30 AM Page 1054 1054 | Answers to Selected Exercises Chapter 2 Case Study Follow-Up 1. const string BLACK = "%%%%%%%%"; // Define a line of a black square 2. const string WHITE = "........"; // Define a line of a white square 3. Move the first five output statements to the end of the program. 4. const string BLACK = "**********"; // Define a line of a black square const string WHITE = " "; // Define a line of a white square 5. //****************************************************************** // Chessboard program // This program prints a chessboard pattern that is built up from // basic strings of white and black characters. //****************************************************************** #include <iostream> #include <string> using namespace std; const string BLACK = "********"; // Define a line of a black square const string WHITE = " "; // Define a line of a white square const string BLACK_BLANK = "** **"; // Define a constant of embedded // blanks int main () { string whiteRow; // A row beginning with a white square string blackRow; // A row beginning with a black square string blackBlankRow; // A black first row with mixed squares string whiteBlankRow; // A white first row with mixed squares // Create a white-black row by concatenating the basic strings whiteRow = WHITE + BLACK + WHITE + BLACK + WHITE + BLACK + WHITE + BLACK; // Create a white-black row with interior blanks in the blacks whiteBlankRow = WHITE + BLACK_BLANK + WHITE + BLACK_BLANK + WHITE + BLACK_BLANK + WHITE + BLACK_BLANK; // Create a black-white row with interior blanks in the blacks blackBlankRow = BLACK_BLANK + WHITE + BLACK_BLANK + WHITE + BLACK_BLANK + WHITE + BLACK_BLANK + WHITE; DalePhatANS_complete 8/18/04 10:30 AM Page 1055 Answers to Selected Exercises | 1055 // Create a black-white row by concatenating the basic strings blackRow = BLACK + WHITE + BLACK + WHITE + BLACK + WHITE + BLACK + WHITE; // Print five white-black rows cout << whiteRow << endl; cout << whiteRow << endl; cout << whiteBlankRow << endl; cout << whiteBlankRow << endl; cout << whiteRow << endl; // Print five black-white rows cout << blackRow << endl; cout << blackRow << endl; cout << blackBlankRow << endl; cout << blackBlankRow << endl; cout << blackRow << endl; // Print five white-black rows cout << whiteRow << endl; cout << whiteRow << endl; cout << whiteBlankRow << endl; cout << whiteBlankRow << endl; cout << whiteRow << endl; // Print five black-white rows cout << blackRow << endl; cout << blackRow << endl; cout << blackBlankRow << endl; cout << blackBlankRow << endl; cout << blackRow << endl; // Print five white-black rows cout << whiteRow << endl; cout << whiteRow << endl; cout << whiteBlankRow << endl; cout << whiteBlankRow << endl; cout << whiteRow << endl; DalePhatANS_complete 8/18/04 10:30 AM Page 1056 1056 | Answers to Selected Exercises // Print five black-white rows cout << blackRow << endl; cout << blackRow << endl; cout << blackBlankRow << endl; cout << blackBlankRow << endl; cout << blackRow << endl; // Print five white-black rows cout << whiteRow << endl; cout << whiteRow << endl; cout << whiteBlankRow << endl; cout << whiteBlankRow << endl; cout << whiteRow << endl; // Print five black-white rows cout << blackRow << endl; cout << blackRow << endl; cout << blackBlankRow << endl; cout << blackBlankRow << endl; cout << blackRow << endl; return 0; } 6. There are 64 characters per line, except for the results of Exercise 4, which would have 80 characters per line. Chapter 3 Exam Preparation Exercises 1. They are simple data types. 2. char, short, int, long. 3. Integer overflow. 4. E signifies an exponent in scientific notation. The digits to the left of the E are multiplied by 10 raised to the power given by the digits to the right of the E. DalePhatANS_complete 8/18/04 10:30 AM Page 1057 Answers to Selected Exercises | 1057 5. integer / constant / floating variable a. const int TRACKS_ON_DISK = 17; integer constant b. float timeOfTrack; floating variable c. const float MAX_TIME_ON_DISK = 74.0; floating constant d. short tracksLeft; integer variable e. float timeLeft; floating variable f. long samplesInTrack; integer variable g. const double SAMPLE_RATE = 262144.5; floating constant 6. Integer division with an integer result, and floating division with a floating result. 7. a.21, b.21.6, c.13.0, d.18, e. 20, f. 22, g.18.0. 8. () unary - [ * / % ] [ + - ] 9. True. 10. a. vi, b.ii, c. vii, d. iv, e. i, f.v, g.iii. 11. The ++operator. 12. You write the name of a data type, followed by an expression enclosed in parentheses. 13. mainreturns an intvalue. 14. 215.00 15. False. When used alone they are equivalent, but used within a larger expression, they can give different results (this is explained more in Chapter 10). 16. string::size_type 17. a. 29 b. 1 c. "ought to start with logic" d. 0 e. "log" f. 1 g. string::npos 18. It tells the stream to print floating-point numbers without using scientific notation. Chapter 3 Programming Warm-Up Exercises 1. (hours * 60 + minutes) * 60 + seconds 2. a. days / 7 b. days % 7 3. dollars * 100 + quarters * 25 + dimes *10 + nickels * 5 + pennies 4. float(dollars * 100 + quarters * 25 + dimes *10 + nickels * 5 + pennies) / 100.0 5. count = count + 3; 6. a. 3 * X + Y b. A * A + 2 * B + C c. ((A + B)/(C – D)) * (X / Y) d. ((A * A + 2 * B + C)/D) / (X * Y) DalePhatANS_complete 8/18/04 10:30 AM Page 1058 1058 | Answers to Selected Exercises e. sqrt(fabs(A – B)) f. pow(X, -cos(Y)) 7. string temp; temp = sentence; first = temp.find("and"); // Get first location // Remove first section of string temp = temp.substr(first + 3, temp.length() – (first + 3)); // Find second location of "and" in shortened string second = temp.find("and"); // Remove next section of string temp = temp.substr(second + 3, temp.length() – (second + 3)); // Adjust second to account for deleting first part of string second = second + first + 3; // Locate third "and" and adjust for prior deletions third = temp.find("and") + second + 3; 8. startOfMiddle = name.find(' ') + 1; 9. cout << "$" << fixed << setprecision(2) << setw(8) << money; 10. cout << setprecision(5) << setw(15) << distance; 11. #include <climits> cout << "INT_MAX = " << INT_MAX << " INT_MIN = " << INT_MIN; 12. //********************************************** // Celsius program // This program outputs the Celsius temperature // corresponding to a given Fahrenheit temperature //********************************************** #include <iostream> using namespace std; int main() { const float FAHRENHEIT = 72.0;

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.