Answers to Mini-Quizzes and Labs



Similar documents
Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Answers to Review Questions Chapter 7

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Chapter One Introduction to Programming

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

7.7 Case Study: Calculating Depreciation

Moving from C++ to VBA

6. Control Structures

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

Iteration CHAPTER 6. Topic Summary

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

Lecture 2 Notes: Flow of Control

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

Appendix K Introduction to Microsoft Visual C++ 6.0

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

While Loop. 6. Iteration

Passing 1D arrays to functions.

VB.NET Programming Fundamentals

I PUC - Computer Science. Practical s Syllabus. Contents

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Chapter 5 Functions. Introducing Functions

Sales Person Commission

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

C++ Input/Output: Streams

Chapter 8 Selection 8-1

Ch 7-1. Object-Oriented Programming and Classes

Computer Programming C++ Classes and Objects 15 th Lecture

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

C++ Language Tutorial

Conditions & Boolean Expressions

C++FA 5.1 PRACTICE MID-TERM EXAM

Common Beginner C++ Programming Mistakes

Sequential Program Execution

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

13 Classes & Objects with Constructors/Destructors

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

PIC 10A. Lecture 7: Graphics II and intro to the if statement

The Payroll Program. Payroll

Informatica e Sistemi in Tempo Reale

Compiler Construction

Basics of I/O Streams and File I/O

The if Statement and Practice Problems

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

An Incomplete C++ Primer. University of Wyoming MA 5310

AP Computer Science Java Subset

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Test #4 November 20, True or False (2 points each)

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

CISC 181 Project 3 Designing Classes for Bank Accounts

Part I. Multiple Choice Questions (2 points each):

Sources: On the Web: Slides will be available on:

Appendix M: Introduction to Microsoft Visual C Express Edition

Comp151. Definitions & Declarations

The While Loop. Objectives. Textbook. WHILE Loops

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Example of a Java program

Chapter 2: Elements of Java

Object Oriented Software Design

COMPUTER SCIENCE 1999 (Delhi Board)

Computer Programming I

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

F ahrenheit = 9 Celsius + 32

Introduction to Java

Visual Logic Instructions and Assignments

Chapter 2 Introduction to Java programming

JavaScript: Control Statements I

CS 241 Data Organization Coding Standards

LOOPS CHAPTER CHAPTER GOALS

Microsoft Excel - XP Intermediate

UEE1302 (1102) F10 Introduction to Computers and Programming

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Goals for This Lecture:

EP241 Computer Programming

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Java Basics: Data Types, Variables, and Loops

Moving from CS 61A Scheme to CS 61B Java

Chapter 5. Selection 5-1

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

Conditional Statements Summer 2010 Margaret Reid-Miller

5 Arrays and Pointers

Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.

Introduction to Microsoft Jet SQL

CS170 Lab 11 Abstract Data Types & Objects

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Curriculum Map. Discipline: Computer Science Course: C++

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

Embedded SQL. Unit 5.1. Dr Gordon Russell, Napier University

Transcription:

Answers Answers to Mini-Quizzes and Labs Answers to Chapter 1 Mini-Quizzes Mini-Quiz 1-1 1. machine 2. a. procedure-oriented 3. b. object-oriented 4. compiler Mini-Quiz 1-2 1. sequence, selection, repetition 2. sequence 3. algorithm 4. repetition 5. repetition 6. selection

2 Answers Answers to Mini-Quizzes and Labs Answers to Chapter 1 Labs LAb 1-1 stop and Analyze 1. sequence and repetition 2. 2100, 315, and 1785 3. Change the first line to repeat for (the first 10 customers buying a TV). 4. Change the second line to enter the original price of the TV and the discount rate. Then, replace 15% in the third line with the discount rate. LAb 1-2 Plan and Create repeat (10 times) enter the salesperson s name and sales if (the sales are greater than 10,000) calculate the bonus by multiplying the sales by 10% calculate the bonus by multiplying the sales by 5% end if display the salesperson s name and bonus end repeat LAb 1-3 Modify You can use either of the following algorithms. The modifications are shaded in each. Algorithm 1 repeat for (each customer buying a TV) enter the original price of the TV if (the customer is a store employee) calculate the discount by multiplying the original price by 25% calculate the discount by multiplying the original price by 15% end if calculate the total due by subtracting the discount from the original price print a bill showing the original price, discount, and total due end repeat

Answers to Chapter 2 Mini-Quizzes 3 Algorithm 2 repeat for (each customer buying a TV) enter the original price of the TV if (the customer is not a store employee) calculate the discount by multiplying the original price by 15% calculate the discount by multiplying the original price by 25% end if calculate the total due by subtracting the discount from the original price print a bill showing the original price, discount, and total due end repeat LAb 1-4 what s Missing? The missing instruction is shaded. repeat (3 times) walk forward one complete step end repeat if (Ginger is on the bench) gently shove Ginger off the bench end if repeat (2 times) turn left 90 degrees end repeat sit down on the bench Answers to Chapter 2 Mini-Quizzes Mini-Quiz 2-1 1. Output: raise new salary Input: current salary raise percentage 2. Output: average score Input: midterm score final score 3. Output: 10% tip 15% tip 20% tip Input: customer bill 4. Output: yearly savings Input: amount saved per day number of days in the year

4 Answers Answers to Mini-Quizzes and Labs Mini-Quiz 2-2 1. input/output 2. rectangular 3. 4. Input Processing Output current salary Processing items: none raise raise percentage new salary Algorithm: 1. enter the current salary and raise percentage 2. calculate the raise by multiplying the current salary by the raise percentage 3. calculate the new salary by adding the raise to the current salary 4. display the raise and new salary Input Processing Output midterm score Processing items: average score final score sum Algorithm: start enter midterm score and final score sum = midterm score + final score average score = sum / 2 display average score stop

Answers to Chapter 2 Labs 5 Mini-Quiz 2-3 1. 2. current salary raise percentage raise new salary 32600.05 1630 34230 54700.02 1094 55794 midterm score final score sum average score 75 83 158 79 98 93 191 95.5 Answers to Chapter 2 Labs 2. 3. LAb 2-1 stop and Analyze 1. quantity sold item cost item selling price price and cost difference profit 100 5 8 3 300 650 2.50 3.75 1.25 812.50 The algorithm will display 300 using the first set of input values. It will display 812.50 using the second set of input values. Input Processing Output quantity sold Processing items: none price and cost difference item cost profit item selling price Algorithm: 1. enter the quantity sold, item cost, and item selling price 2. calculate the price and cost difference by subtracting the item cost from the item selling price 3. calculate the profit by multiplying the price and cost difference by the quantity sold 4. display the price and cost difference and profit Input Processing Output quantity sold Processing items: none profit item cost item selling price Algorithm: 1. enter the quantity sold, item cost, and item selling price 2. calculate the profit by subtracting the item cost from the item selling price, and then multiplying the result by the quantity sold 3. display the profit quantity sold item cost item selling price profit

6 Answers Answers to Mini-Quizzes and Labs LAb 2-2 Plan and Create No answer required. LAb 2-3 Modify Input Processing Output number of doughnuts ordered Processing items: total number of items ordered number of muffins ordered doughnut cost total cost doughnut price muffin cost muffin price Algorithm: 1. enter the number of doughnuts ordered, number of muffins ordered, doughnut price, and muffin price 2. calculate the total number of items ordered by adding together the number of doughnuts ordered and number of muffins ordered 3. calculate the doughnut cost by multiplying the number of doughnuts ordered by the doughnut price 4 calculate the muffin cost by multiplying the number of muffins ordered by the muffin price 5. calculate the total cost by adding the doughnut cost to the muffin cost 6. display the total number of items ordered and total cost number of number of doughnut muffin doughnuts ordered muffins ordered price price 4 2 0.50 0.55 0 12 0.60 0.70 total number of doughnut cost muffin cost items ordered total cost 2 1.10 6 3.10 0 8.40 12 8.40

Answers to Chapter 2 Labs 7 LAb 2-4 what s Missing? Input Processing Output shortbread sold Processing items: shortbread contribution pecan sandies sold total sold pecan sandies contribution chocolate mint sold chocolate mint contribution Algorithm: 1. enter shortbread sold, pecan sandies sold, and chocolate mint sold 2. calculate the total sold by adding together shortbread sold, pecan sandies sold, and chocolate mint sold 3. calculate shortbread contribution by dividing shortbread sold by total sold, and then multiplying the result by 100 4. calculate pecan sandies contribution by dividing pecan sandies sold by total sold, and then multiplying the result by 100 5. calculate chocolate mint contribution by dividing chocolate mint sold by total sold, and then multiplying the result by 100 6. display shortbread contribution, pecan sandies contribution, and chocolate mint contribution LAb 2-5 Desk-Check restaurant bill sales tax bill before sales tax 10% tip 15% tip 20% tip 102.50 5.80 96.70 9.67 14.51 19.34 56.78 2.18 54.60 5.46 8.19 10.92 LAb 2-6 Debug first number second number third number sum average 33 56 70 159 53

8 Answers Answers to Mini-Quizzes and Labs Answers to Chapter 3 Mini-Quizzes Mini-Quiz 3-1 1. one 2. a. salestax 3. d. TAX_RATE 4. variables and named constants Mini-Quiz 3-2 1. a. True 2. b. 11011 3. 72, 01001000 4. d. both a and c Mini-Quiz 3-3 1. a. $ 2. d. all of the above 3. 3 4. int population = 0; 5. const double INTEREST_RATE = 0.05; 6. $5 Answers to Chapter 3 Labs LAb 3-1 stop and Analyze 1. The problem requires five memory locations. 2. The problem requires one named constant for the item cost. A named constant is appropriate because the item cost will always be $5.45. The remaining four input, processing, and output items require variables. Variables were chosen for these items so that their values can vary during runtime.

Answers to Chapter 3 Labs 9 3. int quantitysold = 0; const double ITEM_COST = 5.45; double sellingprice = 0.0; double difference = 0.0; double profit = 0.0; LAb 3-2 Plan and Create No answer required. LAb 3-3 Modify The modifications made to Figures 3-18 and 3-21 are shaded. Input Processing Output commission rate Processing items: none commission sales amount Algorithm: 1. enter the commission rate and sales amount 2. calculate the commission by multiplying the sales amount by the commission rate 3. display the commission IPO chart information C++ instructions Input commission rate double CommRate = 0.0; sales amount double sales = 0.0; Processing none Output commission double commission = 0.0; LAb 3-4 what s Missing? The missing statement is shaded. IPO chart information C++ instructions Input height double height = 0.0; radius double radius = 0.0; pi (3.14) const double PI = 3.14;

10 Answers Answers to Mini-Quizzes and Labs Processing none Output volume double volume = 0.0; LAb 3-5 Desk-Check Algorithm: 1. enter the height and radius 2. calculate the volume by multiplying the radius by itself, and then multiplying the result by pi, and then multiplying that result by the height 3. display the volume height radius pi volume 9 6 3.14 1017.36 17 15 3.14 12010.50 LAb 3-6 Debug The modifications made to Figure 3-23 are shaded in the C++ instructions column. IPO chart information C++ instructions Input first number double first = 0.0; second number double second = 0.0; third number double third = 0.0; Processing sum double sum = 0.0; Output average double average = 0.0; Answers to Chapter 4 Mini-Quizzes Mini-Quiz 4-1 1. a. cin >> population; 2. d. cout << quantity; 3. d. all of the above 4. <<

Answers to Chapter 4 Labs 11 Mini-Quiz 4-2 1. totaldue = 2.5 * quantity; 2. totaldue = 2.5 * static_cast<double>(quantity); 3. The expression will evaluate to 5.5. It should evaluate to 6. The expression evaluates incorrectly because dividing the integer 9 by the integer 2 results in the integer 4 rather than in the double number 4.5. Adding 1.5 to 4 results in the incorrect answer of 5.5. 4. You can use any of the following expressions. You can also use the static_cast operator to type cast at least one of the integers in the expression. 9.0 / 2.0 + 1.5 9.0 / 2 + 1.5 9 / 2.0 + 1.5 5. ordered -= 7; Mini-Quiz 4-3 1. syntax 2. source 3. braces Answers to Chapter 4 Labs LAb 4-1 stop and Analyze 1. 1. The quantity integer (10) is implicitly promoted to the double number 10.0. 2. The result of Step 1 (10.0) is multiplied by the double number stored in the itemcost variable (5.35), giving 53.5. 3. The integer 5 is implicitly promoted to the double number 5.0 4. The result of Step 2 (53.5) is added to the result of Step 3 (5.0), giving 58.5. 5. The result of Step 4 (58.5) is assigned to the amountdue variable. The value is correct. 2. 1. The total integer (30) is divided by the integer 3, giving 10. 2. The result of Step 1 (10) is assigned to the total variable. The value is correct.

12 Answers Answers to Mini-Quizzes and Labs 3. 1. The integer 2 is implicitly promoted to the double number 2.0. 2. The result of Step 1 (2.0) is divided into the double number stored in the store2sales variable (8325.72), giving 4162.86. 3. The result of Step 2 (4162.86) is added to the double number stored in the store1sales variable (5678.43), giving 9841.29. 4. The result of Step 3 is assigned to the avgsales variable. The value is not correct. To fix the assignment statement, include parentheses around the addition operation, like this: avgsales = (store1sales + store2sales) / 2; 4. 1. The midterm integer (74) is added to the final integer (93), giving 167. 2. The result of Step 1 (167) is divided by 2, giving 83. 3. The result of Step 2 is assigned to the average variable. The value is not correct. Two ways you can fix the statement are shown here: average = (midterm + final) / 2.0; average = static_cast<double>(midterm + final) / 2; LAb 4-2 Plan and Create No answer required. LAb 4-3 Modify The modifications made to the Lab4-2.cpp file are shaded. 1 //Lab4-3.cpp - displays a salesperson's commission 2 //Created/revised by <your name> on <current date> 3 4 #include <iostream> 5 using namespace std; 6 7 int main() 8 9 //declare variables 10 double commrate = 0.0; 11 double sales = 0.0; 12 double commission = 0.0; 13 14 //enter input items 15 cout << "Sales amount: ";

Answers to Chapter 4 Labs 13 16 cin >> sales; 17 cout << "Commission rate (in decimal form): "; 18 cin >> commrate; 19 20 //calculate and display the commission 21 commission = sales * commrate; 22 cout << "Commission: $" 23 << commission << endl; 24 25 return 0; 26 } //end of main function LAb 4-4 what s Missing? //Lab4-4.cpp - displays the volume of a cylinder //Created/revised by <your name> on <current date> #include <iostream> using namespace std; int main() const double PI = 3.14; double height = 0.0; double radius = 0.0; double volume = 0.0; cout << "Height: "; cin >> height; cout << "Radius: "; cin >> radius; volume = PI * radius * radius * height; cout << "Volume: " << volume << endl; return 0; } //end of main function LAb 4-5 Desk-Check num result1 result2 result3 75 0 0 0.0 1 37 37.5

14 Answers Answers to Mini-Quizzes and Labs LAb 4-6 Debug To debug the program, you need to convert at least one of the items on the right side of the assignment operator to the double data type. For example, you can use any of the following: area = base * height / 2.0; area = static_cast<double>(base) * height / 2; area = base * static_cast<double>(height) / 2; area = static_cast<double>(base) * static_ cast<double>(height) / 2.0; Answers to Chapter 5 Mini-Quizzes Mini-Quiz 5-1 1. end if 2. b. False 3. a. diamond 4. b. single-alternative 5. a. dual-alternative Mini-Quiz 5-2 1. a. braces 2. d. if (age == 21) 3. b. if (price >= 12.75) 4. c.!= 5. b. >= Mini-Quiz 5-3 1. false 2. true 3. false 4. b. if (age >= 30 && age <= 40) 5. a. if (code == 'R' code == 'r')

Answers to Chapter 5 Labs 15 Mini-Quiz 5-4 1. d. cout << fixed << setprecision(2); 2. c. letter = tolower(letter); 3. d. 34.650000 Answers to Chapter 5 Labs LAb 5-1 stop and Analyze 1. The 0.2 rate will be assigned to the rate variable when the user enters either code 1 or code 3. The 0.15 rate will be assigned to the rate variable when the user enters one of the following codes: 2, 4, and 5. 2. The directive on Line 5 is necessary because the program uses the setprecision stream manipulator. 3. The literal constants on Line 19 are enclosed in single quotation marks because the code variable s data type is char. 4. if (code!= '1' && code!= '3') rate = 0.15; rate = 0.2; //end if 5. You can also write the statement on Line 26 as follows: sales = sales * (1 + rate); sales *= (1 + rate); sales += (sales * rate); 6. To omit the rate variable from the program, you would need to remove the double rate = 0.0; and sales = sales + sales * rate; statements. You would also need to change the rate = 0.2; statement to sales = sales + sales * 0.2;, and change the rate = 0.15; statement to sales = sales + sales * 0.15;. LAb 5-2 Plan and Create No answer required.

16 Answers Answers to Mini-Quizzes and Labs LAb 5-3 Modify The changes made to the original program are shaded in the following partial program. int main() const double MEMBER_DISCOUNT_RATE = 0.1; const double NONMEMBER_DISCOUNT_RATE = 0.05; const double SHIP_CHG1 = 0.99; const double SHIP_CHG2 = 4.99; double amtowed = 0.0; char member = ' '; double discount = 0.0; //enter input items cout << "Amount owed before any discount and shipping: "; cin >> amtowed; cout << "Premier Club member (Y/N)? "; cin >> member; //subtract discount if (toupper(member) == 'Y') discount = amtowed * MEMBER_DISCOUNT_RATE; discount = amtowed * NONMEMBER_DISCOUNT_RATE; //end if amtowed -= discount; LAb 5-4 what s Missing? //Lab5-4.cpp - displays the total due for tickets //Created/revised by <your name> on <current date> #include <iostream> #include <iomanip> using namespace std; int main() const int TICKET_PRICE = 75; int tickets = 0; int total = 0; cout << "Number of tickets you want to purchase (the maximum is 10): "; cin >> tickets; if (tickets > 0 && tickets < 11) total = tickets * TICKET_PRICE; cout << fixed << setprecision(0); cout << "Price: $" << total << endl; } cout << "Invalid number of tickets." << endl; //end if return 0; } //end of main function

Answers to Chapter 6 Mini-Quizzes 17 LAb 5-5 Desk-Check quantity 0 5 0 0 When the user enters the number 0, the condition in the first if statement evaluates to true and the statement s true path displays the message The quantity must be greater than 0. Although the correct message already appears on the screen, the computer still evaluates the second if statement s condition, which determines whether the quantity is greater than 0. The second evaluation is unnecessary and makes the code inefficient. You can fix the code by replacing the first //end if comment and the second if clause with an clause. LAb 5-6 Debug To debug the program, change if (code = '2') to if (code == '2'). Answers to Chapter 6 Mini-Quizzes Mini-Quiz 6-1 1. c. in either an outer selection structure s false path or its true path 2. 1. shoot the basketball 2. if (the basketball did not go through the hoop) say Missed it! if (the basketball hit the rim) say So close end if say I did it! if (Maleek was behind the 3-point line) say 3 points for me say 2 points for me end if end if 3. ask the store clerk whether the store accepts your credit card if (the store accepts your credit card) pay for your items using your credit card ask the store clerk whether the store accepts your debit card

18 Answers Answers to Mini-Quizzes and Labs if (the store accepts your debit card) pay for your items using your debit card pay for your items using cash end if end if Mini-Quiz 6-2 1. if (the test score is at least 90) display Great score! if (the test score is at least 70) display Good score display Retake the test end if end if 2. F test score is at least 90 T F test score is at least 70 T display Great score! display Retake the test display Good score 3. if (score >= 90) cout << "Great score!" << endl; if (score >= 70) cout << "Good score" << endl; cout << "Retake the test" << endl; //end if //end if 4. a. membership status, day of the week

Answers to Chapter 6 Labs 19 Mini-Quiz 6-3 1. Using a compound condition rather than a nested selection structure Reversing the decisions in the outer and nested selection structures Using an unnecessary nested selection structure Including an unnecessary comparison in a condition 2. Algorithm A in Figure 6-19 is inefficient because the nested selection structure is unnecessary. If the first selection structure s condition evaluates to false, it means that the basketball did not go through the hoop. Therefore, there is no need for a nested selection structure that determines whether the basketball did not go through the hoop. 3. Algorithm B in Figure 6-19 will not give you the same results as the algorithm shown in Figure 6-2. Algorithm B has Maleek saying I did it! and 3 points for me even when the basketball does not go through the hoop. 4. Algorithm C in Figure 6-19 will give you the same results as the algorithm shown in Figure 6-2. Mini-Quiz 6-4 1. if (score >= 90) cout << "Great score!" << endl; if (score >= 70) cout << "Good score" << endl; if (score >= 0) cout << "Retake the test" << endl; cout << "Invalid test score" << endl; //end if 2. b. case 'B': 3. break Answers to Chapter 6 Labs LAb 6-1 stop and Analyze 1. The program will display the number 11.46 when the ID is the number 11. 2. if (id == 1) price = 50.55; if (id == 2 id == 9) price = 12.35; if (id == 5 id == 7 id ==11) price = 11.46;

20 Answers Answers to Mini-Quizzes and Labs price = -1 //end if //end if //end if 3. if (id == 1) price = 50.55; if (id == 2 id == 9) price = 12.35; if (id == 5 id == 7 id == 11) price = 11.46; price = -1; //end if 4. switch (id) case 1: price = 50.55; break; case 2: case 9: price = 12.35; break; case 5: case 7: case 11: price = 11.46; break; default: price = -1; } //end switch 5. switch (id) case 1: price = 50.55; cout << price << endl; break; case 2: case 9: price = 12.35; cout << price << endl; break; case 5: case 7: case 11: price = 11.46; cout << price << endl; break; default: cout << "Invalid ID" << endl; } //end switch

Answers to Chapter 6 Labs 21 LAb 6-2 Plan and Create No answer required. LAb 6-3 Modify //Lab6-3.cpp - displays the price of a pizza //Created/revised by <your name> on <current date> #include <iostream> #include <iomanip> using namespace std; int main() char size = ' '; char coupon = ' '; double price = 0.0; cout << "M(edium) or L(arge) pizza? "; cin >> size; size = toupper(size); if (size!= 'M' && size!= 'L') cout << "Please enter either M or L." << endl; if (size == 'M') price = 9.99; //large pizza price = 12.99; //end if cout << "$2 coupon (Y/N)? "; cin >> coupon; if (toupper(coupon) == 'Y') price -= 2; //end if cout << fixed << setprecision(2); cout << "Price: $" << price << endl; } //end if return 0; } //end of main function

22 Answers Answers to Mini-Quizzes and Labs LAb 6-4 what s Missing? //Lab6-4.cpp - displays the price of a ticket //Created/revised by <your name> on <current date> #include <iostream> using namespace std; int main() int age = 0; int price = 0; cout << "Age (years): "; cin >> age; if (age < 0) cout << "Invalid age" << endl; if (age > 64) price = 6; if (age > 3) price = 9; price = 0; //end if cout << "Price: $" << price << endl; } //end if return 0; } //end of main function LAb 6-5 Desk-Check number 0 2 4 0 5 10 0 100 50

Answers to Chapter 7 Mini-Quizzes 23 LAb 6-6 Debug The modifications are shaded in the code. //Lab6-6.cpp -displays the salary associated with a code //Valid codes Salary //1 $45,000 //2, 5 $33,000 //3, 4 $25,000 //Created/revised by <your name> on <current date> #include <iostream> using namespace std; int main() int code = 0; cout << "Enter the code (1 through 5): "; cin >> code; //display salary if (code == 1) cout << "$45,000" << endl; if (code == 2 code == 5) cout << "$33,000" << endl; if (code == 3 code == 4) cout << "$25,000" << endl; cout << "Entry error" << endl; //end if return 0; } //end of main function Answers to Chapter 7 Mini-Quizzes Mini-Quiz 7-1 1. 1. print the first page 2. repeat while (there is another page to print) print the next page end repeat say Done printing

24 Answers Answers to Mini-Quizzes and Labs 2. 1. print the first page 2. repeat while (there is another page to print) if (the next page is not page 3) print the next page end if end repeat say Done printing 3. 1. shoot the basketball 2. repeat while (the basketball did not go through the hoop) say Missed it! shoot the basketball end repeat 3. say I did it! Mini-Quiz 7-2 1. while (ordered > 100) 2. while (quantity >= 0) 3. while (instock > reorder) 4. while (toupper(letter) == 'Y') [You can also use while (tolower(letter) == 'y') or while (letter == 'Y' letter == 'y').] 5. a. 9 Mini-Quiz 7-3 1. b. counter 2. quantity += 10; (or quantity = quantity + 10;) 3. total -= 5; (or total = total - 5; or total += -5; or total = total + -5;) 4. totalpurchases += purchases; (or totalpurchases = totalpurchases + purchases;)

Answers to Chapter 7 Labs 25 Mini-Quiz 7-4 1. while (evennum < 9) cout << evennum << endl; evennum += 2; (or evennum = evennum + 2;) } //end while 2. a. for (int x = 10; x <= 100; x = x + 10) 3. d. 110 4. for (int x = 25; x > 0; x = x 5) (You can also use x -= 5, x += 5, or x = x + 5 as the update argument.) 5. 0 6. for (int num = 2; num < 9; num += 2) (You can also use num = num + 2 as the update argument.) Answers to Chapter 7 Labs LAb 7-1 stop and Analyze 1. The program s counter and accumulator variables are named day and totaltexts, respectively. 2. The for clause s condition argument can also be phrased as day <= 7. 3. The for statement s counter variable is declared at the beginning of the program because it needs to be used after the for loop ends. More specifically, it needs to be used by the statement on Line 24, which calculates the average number of text messages. 4. The average number of text messages is 74. day dailytexts totaltexts average 0 0 0 0.0 1 76 76 74.0 2 80 156 3 100 256 4 43 299 5 68 367 6 70 437 7 79 516 8 5. The program displays 74.

26 Answers Answers to Mini-Quizzes and Labs 6. The build or compile operation was not successful because the compiler does not recognize the day variable used in Line 24. When the for loop ended, that variable was removed from the computer s internal memory. 8. The program does not work correctly because it prompts the user to enter the number of text messages for days from 0 through 7, rather than from 1 through 7. To fix the program change the day variable s declaration statement to int day = 1;. LAb 7-2 Plan and Create No answer required. LAb 7-3 Modify //Lab7-3.cpp - calculates the average number of text //messages sent each day for 7 days //Created/revised by <your name> on <current date> #include <iostream> #include <iomanip> using namespace std; int main() int day = 1; int totaltexts = 0; int dailytexts = 0; double average = 0.0; while (day < 8) cout << "How many text messages did you send on day " << day << "? "; cin >> dailytexts; totaltexts += dailytexts; day += 1; } //end while average = static_cast<double>(totaltexts) / (day - 1); cout << fixed << setprecision(0); cout << endl << "You sent approximately " << average << " text messages per day." << endl; return 0; } //end of main function

Answers to Chapter 7 Labs 27 LAb 7-4 what s Missing? //Lab7-4.cpp - displays the average electric bill //Created/revised by <your name> on <current date> #include <iostream> #include <iomanip> using namespace std; int main() double bill = 0.0; double totalbills = 0.0; double avgbill = 0.0; int months = 0; cout << "Bill for month 1: "; cin >> bill; while (bill >= 0.0) totalbills += bill; months += 1; cout << "Bill for month " << months + 1 << ": "; cin >> bill; } //end while if (months > 0) avgbill = totalbills / months; cout << fixed << setprecision(2); cout << "Average electric bill for " << months << " months: $" << avgbill << endl; } cout << "No bill amount entered." << endl; //end if return 0; } //end of main function LAb 7-5 Desk-Check The original code contains an error because it will not display the number 12. To correct the code, change the for statement s condition to number <= 12. First desk-check: Corrected desk-check: number number 2 2 4 4 6 6 8 8 10 10 12 12 14

28 Answers Answers to Mini-Quizzes and Labs LAb 7-6 Debug To debug the program, enter a cin >> price; statement below the cout << "Next price: "; statement. Answers to Chapter 8 Mini-Quizzes Mini-Quiz 8-1 1. The condition will be evaluated four times. The algorithm will display the numbers 5, 8, and 9, followed by the word Done. 2. The condition will be evaluated once. The algorithm will display the word Done. 3. The condition will be evaluated three times. The algorithm will display the numbers 5, 8, and 9, followed by the word Done. 4. The condition will be evaluated once. The algorithm will display the number 0 followed by the word Done. Mini-Quiz 8-2 1. a. do 2. d. semicolon 3. } while (ordered <= inventory); 4. } while (toupper(letter) == 'Y'); Mini-Quiz 8-3 1. b. False 2. b. nested, outer 3. a. outer, nested

Answers to Chapter 8 Labs 29 Answers to Chapter 8 Labs LAb 8-1 stop and Analyze 1. The program contains three loops. Two of the loops are nested. 2. Desk-check: maxrows row space asterisk 0 0 0 0 3 1 1 1 2 2 0 3 3 1 0 2 1 0 2 1 0 2 1 3 The program will display the following pattern of asterisks: * * * * * * 3. The program displays the pattern of asterisks shown above. 4. The program displays the following pattern of asterisks: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 5. //Lab8-1.cpp //Created/revised by <your name> on <current date> #include <iostream> using namespace std; int main() int maxrows = 0; int row = 0; cout << "Maximum number of rows: "; cin >> maxrows; while (row < maxrows) for (int space = 0; space < maxrows - row; space += 1) cout << " "; //end for

30 Answers Answers to Mini-Quizzes and Labs for (int asterisk = 0; asterisk <= row; asterisk += 1) cout << "* "; //end for cout << endl; row += 1; } //end while return 0; } //end of main function LAb 8-2 Plan and Create No answer required. LAb 8-3 Modify //Lab8-3.cpp - displays a person's total //earnings before retirement at age 65, //using annual raise rates of 3%, 4%, and 5% //Created/revised by <your name> on <current date> #include <iostream> #include <iomanip> using namespace std; int main() int age = 0; int currentsalary = 0; int yearstoretire = 0; double newsalary = 0.0; double total = 0.0; double rate = 0.0; cout << fixed << setprecision(0); cout << "Current age in years (1 to 64): "; cin >> age; if (age < 1 age > 64) cout << "Please enter an age from 1 to 64." << endl; cout << "Current salary as a whole number: "; cin >> currentsalary; cout << endl; yearstoretire = 65 - age; rate = 0.03; do newsalary = currentsalary; //year 1 salary total = currentsalary; //year 1 salary

Answers to Chapter 8 Labs 31 for (int year = 2; year <= yearstoretire; year += 1) newsalary *= (1 + rate); total += newsalary; } //end for cout << "Total with a " << rate * 100 << "% annual raise: $" << total << endl; rate += 0.01; } while (rate < 0.06); } //end if return 0; } //end of main function LAb 8-4 what s Missing? //Lab8-4.cpp - displays a pattern of numbers //Created/revised by <your name> on <current date> #include <iostream> using namespace std; int main() int maxrows = 0; cout << "How many rows? "; cin >> maxrows; for (int row = 1; row <= maxrows; row += 1) for (int col = 1; col <= row; col += 1) cout << col; //end for cout << endl; } //end for return 0; } //end of main function LAb 8-5 Desk-Check Desk-check: sumx sumy x y 0 0 2 1 2 1 4 3 6 4 6 5 12 5 8 1 8 3 9 5 12 1 3 5

32 Answers Answers to Mini-Quizzes and Labs The program will display the following: sumx value: 12 sumy value: 12 When the outer loop ends, the x variable contains the number 8. When the nested loop ends, the y variable contains the number 5. LAb 8-6 Debug To debug the program, cut the month += 1; statement from the nested loop and paste it below the cout << endl; statement in the outer loop. Also, change the totalsales += totalsales + sales; statement to either totalsales = totalsales + sales; or totalsales += sales;. Answers to Chapter 9 Mini-Quizzes Mini-Quiz 9-1 1. b. sqrt(16.0) 2. c. 25 + rand() % (50 25 + 1) 3. d. none of the above 4. a. #include <ctime> Mini-Quiz 9-2 1. d. all of the above 2. a. double getarea() 3. double getgrosspay(int hours, double rate) 4. return gross;

Answers to Chapter 9 Labs 33 Mini-Quiz 9-3 1. b. area = getarea(); 2. c. double getarea(); 3. cout << getarea(); 4. double getgrosspay(int hours, double rate); or double getgrosspay (int, double); 5. weekgross = getgrosspay(40, payrate); Answers to Chapter 9 Labs LAb 9-1 stop and Analyze 1. The statements on Lines 9 and 10 are function prototypes, and they are necessary because the getarea and getdiameter functions are defined below the main function. 2. The statement on Line 9 could also be written as follows: double getarea(double);. 3. Without the outer selection structure, the program will display the following: Diameter: 20. 4. The scope of the choice and radius variables is the main function (Lines 17 through 36). The lifetime is the same as the main function s lifetime, which means that the variables will be removed from the computer s memory when the main function ends. 5. The scope of the rad variable used in the getarea function is the function itself (Lines 40 through 45). Its lifetime is the same as the getarea function s lifetime, which means it will be removed from the computer s memory when the function ends. 6. The scope of the PI constant and the area variable is the getarea function (Lines 43 through 45). Their lifetime is the same as the getarea function s lifetime, which means they will be removed from the computer s memory when the function ends. 7. The scope of the rad variable used in the getdiameter function is the function itself (Lines 48 through 50). Its lifetime is the same as the getdiameter function s lifetime, which means it will be removed from the computer s memory when the function ends. 9. //Lab9-1.cpp - circle calculations //Created/revised by <your name> on <current date> #include <iostream> #include <cmath> using namespace std; //function prototypes double getarea(double rad); double getdiameter(double rad); double getcircumference(double rad);

34 Answers Answers to Mini-Quizzes and Labs int main() int choice = 0; double radius = 0.0; cout << "1 Circle area" << endl; cout << "2 Circle diameter" << endl; cout << "3 Circle circumference" << endl; cout << "Enter your choice (1, 2, or 3): "; cin >> choice; if (choice < 1 choice > 3) cout << "Invalid choice" << endl; cout << "Radius: "; cin >> radius; if (choice == 1) cout << "Area: " << getarea(radius); if (choice == 2) cout << "Diameter: " << getdiameter(radius); cout << "Circumference: " << getcircumference(radius); //end if cout << endl; } //end if return 0; } //end of main function //*****function definitions***** double getarea(double rad) const double PI = 3.141593; double area = 0.0; area = PI * pow(rad, 2); return area; } //end getarea function double getdiameter(double rad) return 2 * rad; } //end getdiameter function double getcircumference(double rad) const double PI = 3.141593; double circumference = 0.0; circumference = 2 * PI * rad; return circumference; } //end getcircumference function

Answers to Chapter 9 Labs 35 LAb 9-2 Plan and Create No answer required. LAb 9-3 Modify //Lab9-3.cpp - displays two monthly car payments //Created/revised by <your name> on <current date> #include <iostream> #include <cmath> #include <iomanip> using namespace std; //function prototype double getpayment(int, double, int); int main() int carprice = 0; int rebate = 0; double creditrate = 0.0; double dealerrate = 0.0; int term = 0; double creditpayment = 0.0; double dealerpayment = 0.0; char another = 'Y'; while (another == 'Y') cout << "Car price (after any trade-in): "; cin >> carprice; cout << "Rebate: "; cin >> rebate; cout << "Credit union rate: "; cin >> creditrate; cout << "Dealer rate: "; cin >> dealerrate; cout << "Term in years: "; cin >> term; if (creditrate >= 1) creditrate /= 100; //end if if (dealerrate >= 1) dealerrate /= 100; //end if

36 Answers Answers to Mini-Quizzes and Labs //call function to calculate payments creditpayment = getpayment(carprice - rebate, creditrate / 12, term * 12); dealerpayment = getpayment(carprice, dealerrate / 12, term * 12); //display payments cout << fixed << setprecision(2) << endl; cout << "Credit union payment: $" << creditpayment << endl; cout << "Dealer payment: $" << dealerpayment << endl; if (creditpayment < dealerpayment) cout << "Take the rebate and finance through the credit union."; if (creditpayment > dealerpayment) cout << "Don't take the rebate. Finance through the dealer."; cout << "You can finance through the dealer or the credit union."; //end if cout << endl; cout << "Calculate another set of payments (Y/N)?"; cin >> another; another = toupper(another); } //end while return 0; } //end of main function //*****function definitions***** double getpayment(int prin, double monthrate, int months) //calculates and returns a monthly payment double monthpay = 0.0; monthpay = prin * monthrate / (1 - pow(monthrate + 1, -months)); return monthpay; } //end of getpayment function

Answers to Chapter 9 Labs 37 LAb 9-4 what s Missing? //Lab9-4.cpp - displays total due //Created/revised by <your name> on <current date> #include <iostream> #include <iomanip> using namespace std; double getsalestax(double subtotal); int main() int quantity = 0; double itemprice = 0.0; double totalbeforetax = 0.0; double totaldue = 0.0; cout << "Quantity: "; cin >> quantity; cout << "Item price: "; cin >> itemprice; totalbeforetax = quantity * itemprice; totaldue = totalbeforetax + getsalestax(totalbeforetax); cout << fixed << setprecision(2) << endl; cout << "Total due: $" << totaldue << endl; return 0; } //end of main function //*****function definitions***** double getsalestax(double subtotal) const double TAX_RATE = 0.1; double tax = 0.0; tax = subtotal * TAX_RATE; return tax; } //end of getsalestax function

38 Answers Answers to Mini-Quizzes and Labs LAb 9-5 Desk-Check Desk-check: currenttotal number x current num 0 0 1 100 4 100 4 2 116 3 116 3 3 116 10 110 10 4 110 9 210 9 5 110 5 291 5 6 210 281 210 291 291 281 The code will display 281 as the current total. LAb 9-6 Debug To debug the program, change the statement that calls the getdepreciation function to depreciation = getdepreciation(cost, salvage, lifeyears);. Answers to Chapter 10 Mini-Quizzes Mini-Quiz 10-1 1. void 2. displaytaxes(federaltax, localtax); 3. void displaytaxes(double fedtax, double statetax) 4. b. False Mini-Quiz 10-2 1. void calctaxes(double pay, double &fedtax, double &statetax) 2. calctaxes(gross, federal, state); 3. void calctaxes(double pay, double &fedtax, double &statetax); or void calctaxes(double, double &, double &) 4. b. False

Answers to Chapter 10 Labs 39 Answers to Chapter 10 Labs LAb 10-1 stop and Analyze 1. Lines 10 and 52 indicate whether the variables are passed by value or by reference to the getarea function. 2. The radius variable is passed by value because the receiving functions need to know its value but do not need to change its contents. The circlearea and circlediameter variables are passed by reference because the receiving functions need to store values (either the area or the diameter) inside the variables. 3. The displaychoices function is a void function because it does not need to return a value after completing its task. 4. The getarea and getdiameter functions use the variables that are passed by reference to send information back to the main function. 5. //Lab10-1.cpp - circle calculations //Created/revised by <your name> on <current date> #include <iostream> #include <cmath> using namespace std; //function prototypes void displaychoices(); double getarea(double rad); void getdiameter(double rad, double &diameter); int main() int choice = 0; double radius = 0.0; double circlearea = 0.0; double circlediameter = 0.0; displaychoices(); cout << "Enter your choice (1 or 2): "; cin >> choice; if (choice < 1 choice > 2) cout << "Invalid choice" << endl; cout << "Radius: "; cin >> radius; if (choice == 1) circlearea = getarea(radius); cout << "Area: " << circlearea; }

40 Answers Answers to Mini-Quizzes and Labs getdiameter(radius, circlediameter); cout << "Diameter: " << circlediameter; } //end if cout << endl; } //end if return 0; } //end of main function //*****function definitions***** void displaychoices() cout << "1 Circle area" << endl; cout << "2 Circle diameter" << endl; } //end displaychoices double getarea(double rad) const double PI = 3.141593; double area = 0.0; area = PI * pow(rad, 2); return area; } //end getarea function void getdiameter(double rad, double &diameter) diameter = 2 * rad; } //end getdiameter function LAb 10-2 Plan and Create No answer required. LAb 10-3 Modify //Lab10-3.cpp - displays total owed //Created/revised by <your name> on <current date> #include <iostream> #include <iomanip> using namespace std;

Answers to Chapter 10 Labs 41 //function prototypes void displayoptions(); double getregular(int windows, double price); double getbogo(int windows, double price); int main() int option = 0; int numordered = 0; double winprice = 0.0; double totalowed = 0.0; cout << fixed << setprecision(2); displayoptions(); cout << "Pricing option? "; cin >> option; if (option == 1 option == 2) cout << "Number of windows: "; cin >> numordered; cout << "Price per window: "; cin >> winprice; if (option == 1) totalowed = getregular(numordered, winprice); totalowed = getbogo(numordered, winprice); //end if cout << "Total owed-----> $" << totalowed << endl << endl; } cout << "Invalid option" << endl; //end if return 0; } //end of main function //*****function definitions***** void displayoptions() cout << "Pricing options:" << endl; cout << "1 Regular pricing" << endl; cout << "2 BOGO pricing" << endl; } //end displayoptions

42 Answers Answers to Mini-Quizzes and Labs double getregular(int windows, double price) double total = 0.0; total = windows * price; return total; } //end getregular function double getbogo(int windows, double price) double total = 0.0; total = (windows / 2 + windows % 2) * price; return total; } //end getbogo function LAb 10-4 what s Missing? //Lab10-4.cpp - displays the raise and new salary //Created/revised by <your name> on <current date> #include <iostream> #include <iomanip> using namespace std; //function prototypes void getraise(double current, double rate, double &increase); void getnewpay(double current, double increase, double &newpay); int main() double currentsalary = 0.0; double raiserate = 0.0; double raise = 0.0; double newsalary = 0.0; cout << "Current salary: "; cin >> currentsalary; cout << "Raise rate (in decimal form): "; cin >> raiserate; //get the raise and new salary getraise(currentsalary, raiserate, raise); getnewpay(currentsalary, raise, newsalary); //display the raise and new salary cout << fixed << setprecision(2); cout << "Raise: $" << raise << endl; cout << "New salary: $" << newsalary << endl; return 0; } //end of main function

Answers to Chapter 10 Labs 43 //*****function definitions***** void getraise(double current, double rate, double &increase) increase = current * rate; } //end of getraise function void getnewpay(double current, double increase, double &newpay) newpay = current + increase; } //end of getnewpay function LAb 10-5 Desk-Check The names in black indicate variables that belong to the main function. The names in red indicate variables that belong to the getsquare function. The names in blue indicate variables that belong to the getcube function. The program will display The sum is: 50. cubeanswer sqanswer sum number num num 0 1 1 1 1 2 2 2 2 3 3 3 6 4 14 23 50 LAb 10-6 Debug To debug the program, change the function prototype to either void assigngrade(int pointsearned, char &letter); or void assigngrade(int, char &); and change the function header to void assigngrade(int pointsearned, char &letter). Also change the function call to assigngrade(totalpoints, grade);.

44 Answers Answers to Mini-Quizzes and Labs Answers to Chapter 11 Mini-Quizzes Mini-Quiz 11-1 1. a. int quantities[20] = 0}; 2. quantities[0] 3. quantities[19] 4. quantities[3] = 7; 5. c. total = gettotal(quantities, 20); Mini-Quiz 11-2 1. c. total += orders[2]; 2. c. if (orders[3] > 25) 3. bonus = sales[0] * 0.15; 4. c. if (sub >= 0 && sub < 10) 5. a. while (x < 20) Mini-Quiz 11-3 1. if (prices[x] < lowest) 2. sorting 3. for (int x = 0; x < 10; x += 1) orders[x] -= 3; //end for Answers to Chapter 11 Labs LAb 11-1 stop and Analyze 1. The domestic and international arrays are parallel arrays because the elements in one array are related by their subscripts to the elements in the other array. For example, the first element in both arrays contains the sales made in January; the second element contains the February sales, and so on. 2. The domestic[1] element contains 30200. 3. The total company sales made in February can be calculated by adding the contents of the domestic[1] element to the contents of the international[1] element.

Answers to Chapter 11 Labs 45 4. The highest subscript in the international array is 5. 5. The assignment statement would need to be changed to totalsales += domestic [x 1] + international[x 1];. 6. No answer required. 7. //Lab11-1.cpp - calculates the total sales //Created/revised by <your name> on <current date> #include <iostream> using namespace std; int main() int domestic[6] = 75000, 30200, 67800, 45000, 60000, 67500}; int international[6] = 40000, 75000, 64000, 32600, 47800, 39000}; int totaldomestic = 0; int totalinternational = 0; int totalsales = 0; for (int x = 0; x < 6; x += 1) totaldomestic += domestic[x]; totalinternational += international[x]; } //end for totalsales = totaldomestic + totalinternational; //display total domestic sales, total international //sales, and total sales cout << "Total domestic sales: $" << totaldomestic << endl; cout << "Total international sales: $" << totalinternational << endl; cout << "Total sales: $" << totalsales << endl; return 0; } //end of main function 8. //Lab11-1.cpp - calculates the total sales //Created/revised by <your name> on <current date> #include <iostream> using namespace std; int main() int domestic[6] = 75000, 30200, 67800, 45000, 60000, 67500};

46 Answers Answers to Mini-Quizzes and Labs int international[6] = 40000, 75000, 64000, 32600, 47800, 39000}; int monthsales[6] = 0}; int totaldomestic = 0; int totalinternational = 0; int totalsales = 0; for (int x = 0; x < 6; x += 1) totaldomestic += domestic[x]; totalinternational += international[x]; monthsales[x] = domestic[x] + international[x]; } //end for totalsales = totaldomestic + totalinternational; //display total domestic sales, total international //sales, and total sales cout << "Total domestic sales: $" << totaldomestic << endl; cout << "Total international sales: $" << totalinternational << endl; cout << "Total sales: $" << totalsales << endl << endl; //display total sales made in each month for (int x = 0; x < 6; x += 1) cout << "Month " << x + 1 << " sales: $" << monthsales[x] << endl; } //end for return 0; } //end of main function LAb 11-2 Plan and Create No answer required. LAb 11-3 Modify //Lab11-3.cpp - stores finish times in an array //and displays the average and lowest times //Created/revised by <your name> on <current date> #include <iostream> #include <iomanip> using namespace std;

Answers to Chapter 11 Labs 47 //function prototypes void getaverage(double times[], int numelements, double &avg); void getlowest(double times[], int numelements, double &lowest); int main() double finishtimes[5] = 0.0}; double avgtime = 0.0; double lowesttime = 0.0; //enter finish times for (int x = 0; x < 5; x += 1) cout << "Time for race " << x + 1 << ": "; cin >> finishtimes[x]; } //end for getaverage(finishtimes, 5, avgtime); getlowest(finishtimes, 5, lowesttime); cout << fixed << setprecision(1) << endl; cout << "Average 5K finish time: " << avgtime << endl; cout << "Lowest 5K finish time: " << lowesttime << endl; return 0; } //end of main function //*****function definitions***** void getaverage(double times[], int numelements, double &avg) double total = 0.0; for (int x = 0; x < numelements; x += 1) total += times[x]; //end for avg = total / numelements; } //end of getaverage function void getlowest(double times[], int numelements, double &lowest) lowest = times[0]; for (int x = 1; x < numelements; x += 1) if (times[x] < lowest) lowest = times[x]; //end if //end for } //end of getlowest function

48 Answers Answers to Mini-Quizzes and Labs LAb 11-4 what s Missing? //Lab11-4.cpp - Displays the average stock price //Created/revised by <your name> on <current date> #include <iostream> #include <iomanip> using namespace std; //function prototype double gettotal(double prices[], int numelements); int main() double stockprices[10] = 35.6, 37.8, 39, 38.9, 38.9, 37.8, 37.8, 37.8, 39, 39.5}; double total = 0.0; double average = 0.0; total = gettotal(stockprices, 10); average = total / 10; cout << fixed << setprecision(2); cout << "Average stock price: $" << average << endl; return 0; } //end of main function //*****function definitions***** double gettotal(double prices[], int numelements) double sumprices = 0.0; for (int sub = 0; sub < numelements; sub += 1) sumprices += prices[sub]; //end for return sumprices; } //end of gettotal function LAb 11-5 Desk-Check Desk-check: midterms[0] midterms[1] midterms[2] midterms[3] midterms[4] 0.0 0.0 0.0 0.0 0.0 90.0 88.0 77.0 85.0 45.0 finals[0] finals[1] finals[2] finals[3] finals[4] 0.0 0.0 0.0 0.0 0.0 100.0 68.0 75.0 85.0 32.0

Answers to Chapter 12 Mini-Quizzes 49 averages[0] averages[1] averages[2] averages[3] averages[4] 0.0 0.0 0.0 0.0 0.0 95.0 78.0 76.0 85.0 38.5 X y 0 0 1 1 2 2 3 3 4 4 5 5 The for loop will display the following: Student 1 average: 95 Student 2 average: 78 Student 3 average: 76 Student 4 average: 85 Student 5 average: 38.5 LAb 11-6 Debug To debug the program, change the condition in the for clause to x < 10. Also change the increase += quantities[x]; statement in the for loop to quantities[x] += increase;. Answers to Chapter 12 Mini-Quizzes Mini-Quiz 12-1 1. a. int quantities[6][3] = 0}; 2. 18 3. quantities[0][0] 4. quantities[5][2] 5. quantities[1][0] = 20;

50 Answers Answers to Mini-Quizzes and Labs Mini-Quiz 12-2 1. c. total += purchases[2][1]; 2. c. if (scores[1][2] > 25) 3. bonus = sales[0][1] * 0.15; 4. a. if (row >= 0 && row < 10) Answers to Chapter 12 Labs LAb 12-1 stop and Analyze 1. 39000 2. The total company sales made in February can be calculated by adding the contents of the company[0][1] element to the contents of the company[1][1] element. 3. The highest row subscript in the company array is 1. The highest column subscript is 5. 4. The January international sales are stored in the company[1][0] element. 5. The assignment statement would need to be changed to companysales += company[location][month 1];. 6. No answer required. 7. //Lab12-1.cpp - calculates the total company sales //Created/revised by <your name> on <current date> #include <iostream> using namespace std; int main() int company[2][6] = 75000, 30200, 67800, 45000, 60000, 67500}, 40000, 75000, 64000, 32600, 47800, 39000}}; int companysales = 0; int domesticsales = 0; int internationalsales = 0; for (int month = 0; month < 6; month += 1) domesticsales += company[0][month]; internationalsales += company[1][month]; } //end for companysales = domesticsales + internationalsales;

Answers to Chapter 12 Labs 51 cout << "Domestic sales: $" << domesticsales << endl; cout << "International sales: $" << internationalsales << endl; cout << "Company sales: $" << companysales << endl; return 0; } //end of main function 8. //Lab12-1.cpp - calculates the total company sales //Created/revised by <your name> on <current date> #include <iostream> using namespace std; int main() int company[2][6] = 75000, 30200, 67800, 45000, 60000, 67500}, 40000, 75000, 64000, 32600, 47800, 39000}}; int monthsales[6] = 0 }; int companysales = 0; int domesticsales = 0; int internationalsales = 0; for (int month = 0; month < 6; month += 1) domesticsales += company[0][month]; internationalsales += company[1][month]; monthsales[month] = company[0][month] + company[1][month]; } //end for companysales = domesticsales + internationalsales; cout << "Domestic sales: $" << domesticsales << endl; cout << "International sales: $" << internationalsales << endl; cout << "Company sales: $" << companysales << endl; for (int x = 0; x < 6; x += 1) cout << "Month " << x + 1 << " sales: $" << monthsales[x] << endl; //end for return 0; } //end of main function LAb 12-2 Plan and Create No answer required.