C++ Programming From Problem Analysis to Program Design 8th Edition Malik
Full download at link:
Test Bank: https://testbankpack.com/p/test-bank-for-cprogramming-from-problem-analysis-to-program-design-8thedition-by-malik-isbn-9781337102087/
Solution Manual: https://testbankpack.com/p/solution-manual-forc-programming-from-problem-analysis-to-program-design-8thedition-by-malik-isbn-9781337102087/
Chapter 1
1. a. true; b. false; c. false; d. true; e. false; f. true; g.true; h. true; i. false; j. false; k. true; l. true; m. true; n. true; o. true; p. false; q. true; r. true; s. true
2. CPU.
3. Base 2 or binary.
4. The equivalent machine language program of a high-level language program.
5. In linking, an object program is combined with other programs in the library, used in the program, to create the executable code.
6. Loader
7. #
8. Preprocessor
9. Programming is a process of problem solving.
10. A step-by-step problem-solving process in which a solution is arrived at in a finite amount of time.
11. (1) Analyze and outline the problem and its solution requirements, and design an algorithm to solve the problem. (2) Implement the algorithm in a programming language, such as C++, and verify that the algorithm works. (3) Maintain the program by using and modifying it if the problem domain changes.
12. (1) Thoroughly understand the problem. (2) Understand the problem requirements. (3) If the problem is complex, divide the problem into subproblems and repeat Steps 1 and 2.
13. 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 to get the average. Therefore,
1. Get testScore1, weightTestScore1
2. Get testScore2, weightTestScore2
3. Get testScore3, weightTestScore3
4. Get testScore4, weightTestScore4
5. weightedAverage = testScore1 * weightTestScore1 + testScore2 * weightTestScore2 + testScore3 * weightTestScore3 + testScore4 * weightTestScore4;
14. a. Get quarters
b. Get dimes
c. Get nickels
d. Get pennies
e. changeInPennies =quarters * 25 + dimes * 10 + nickels * 5 + pennies
15. To find the price per square inch, first we need to find the area of the pizza. Then we divide the price of the pizza by the area of the pizza. Let radius denote the radius and area denote the area of the circle, and price denote the price of pizza. Also, let pricePerSquareInch denote the price per square inch.
a. Get radius
b. area = π * radius * radius
c. Get price
d. pricePerSquareInch = price / area
16 To determine the least selling price of a car, we need to know the listing price of the car. The algorithm is as follows:
a. Get listingPrice
b. Calculate the least selling price leastSellingPrice using the formula: leastSellingPrice= listingPrice × 0.85) + 500
17 Suppose that radius denotes radius of the sphere, volume denotes volume of the sphere, and surfaceArea denotes the surface area of the sphere. The following algorithm computes the volume and surface area of the sphere.
Algorithm
C++ Instruction (Code)
1 1. Get the radius. cin >> radius;
2 2. Calculate the volume. volume = (4.0 / 3.0) * 3.1416 * radius * radius * radius;
3 3. Calculate the surface area.
surfaceArea = 4.0 * 3.1416 * radius * radius;
18 Suppose that billingAmount denotes the total billing amount, movingCost denotes moving cost, area denotes the area of the yard that needs to be moved, numOfAppl denotes the number of fertilizing applications, and numOfTrees denotes the number of trees to be planted. The following algorithm computes and outputs the billing amount.
a. Enter the area of the yard.
b. Get area
c. Enter the number of fertilizing applications.
d. Get numOfAppl
e. Enter the number of trees to be planted.
f. Get numOfTrees
g. Calculate the billingAmount using the formula:
billingAmount= (area / 5000) * 35.00 + numOfAppl * 30.00 + numOfTrees * 50.00
19 Suppose that billingAmount denotes the total billing amount, numOfItemsOrdered denotes the number of items ordered, shippingAndHandlingFee denotes the shipping and handling fee, and price denotes the price of an item. The following algorithm computes and outputs the billing amount.
a. Enter the number of items bought.
b. Get numOfItemsOrdered
c billingAmount = 0.0;
d shippingAndHandlingFee = 0.0;
e. Repeat the following for each item bought.
i. Enter the price of the item
ii. Get price
iii. billingAmount = billingAmount + price;
f if billingAmount < 200
shippingAndHandlingFee = 10 * numOfItemsOrdered;
g billingAmount = billingAmount + shippingAndHandlingFee
i. Print billingAmount
20. Suppose amountWithdrawn denotes the amount to be withdrawn, serviceCharge denotes the service charges, if any, and accountBalance denotes the total money in the account
You can now write the algorithm as follows:
a. Get amountWithdrawn.
b. ifamountWithdrawn > 500
Print "The maximum amount that can be drawn is $500" otherwise (if accountBalance <= 0)
Print "Account balance is <= 0. You cannot withdraw any money." otherwise
if (amountWithdrawn > accountBalance)
Print "Insufficient balance. If you withdraw, services charges will be $25.00. Select Yes/No."
if (Yes)
if (amountWithdrawn > 300) serviceCharge = (amountWithdrawn – 300) * 0.04; otherwise serviceCharge = 0;
accountBalance = accountBalance – amountWithdrawn - serviceCharge – 25; Print "Collect your money. "
if (amountWithdrawn > 300) serviceCharge = (amountWithdrawn – 300) * 0.04; otherwise serviceCharge = 0;
accountBalance = accountBalance – amountWithdrawn - serviceCharge; Print "Collect your money."
21 Suppose x1 and x2 are the real roots of the quadratic equation.
a. Get a
b. Get b
c. Get c
d. if (b * b – 4 * a * c < 0)
Print "The equation has no real roots." Otherwise
temp = b * b – 4 * a * c;
x1 = (-b + temp) / (2 * a);
x2 = (-b - temp) / (2 * a);
22 Suppose that tuition denotes the tuition per semester, semesterUnits denotes the average semester units, courseUnits denotes the number of course units, semesterWeeks denotes the number of weeks in a semester, classDaysPerWeek denotes the number of days a class meets in a week, classDaysPerSemester denotes the total number of days a class meets in a semester, costPerUnit denotes the cost of one unit of a course, and costPerClass denotes the cost of one class.
a. Get tuition
b. Get semesterUnits
c. Get semesterWeeks
d. Get courseUnits
e. Get classDaysPerWeek
f Compute costPerUnit using the following formula.
costPerUnit = tuition / semesterUnits;
g. Compute classDaysPerSemester using the following formula.
classDaysPerSemester= classDaysPerWeek * semesterWeeks;
h. Compute costPerClass using the following formula.
costPerClass= (costPerUnit * courseUnits) / classDaysPerSemester;
23 Suppose averageTestScore denotes the average test score, highestScore denotes the highest test score, testScore denotes a test score, sum denotes the sum of all the test scores, 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 the highest test score
i. Get first student’s test score and call it highestTestScore
ii. Repeat the following for each of the remaining students in the 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 the 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. true; d. true; e. false; f. false; g. true; h. true; i. false; j. false; k. true; l. false
2. b, d, e, f
3. b, e
4. A keyword is a reserved word and is defined by the system. A keyword cannot be redefined in a program. A user-defined identifier can be redefined.
5. The identifiers quizNo1 and quizno1 are not the same. C++ is case sensitive. The fifth letter of quizNo1 is uppercase N while the fifth character of quizno1 is lowercase n. So these identifiers are different
6 . a. 22
b. 2
c. 14
d. 8
e. 7.00
f. 21
g. 20
h. 0.00
i. 15.50
7. a. 7
b. 5.50
c. -1.00
d. Not possible. Both the operands of the operator % must be integers. y + z is of type double. Both operands, y + z and x, of %V must be integers
e. 13.50
f. 1
g. Not possible. Both the operands of the operator % must be integers. Because the second operand, z, is a floating-point value, the expression is invalid.
h. 3.00
8. a, b, c, e, i, j, and k are valid;
d, f, and g are invalid because the left side of an expression must be a variable. h is invalid because the operands of the mod operator must be integers.
9. x = 9, y = 5, z = 3, w = -3
10. Variable declarations in Lines 1, 6, and 7 are correct.
Variable declaration in Line 2 is incorrect. Now, B+ is a string, so it must be enclosed in double quotes mark. Also, grade is a char variable and a string cannot be assigned to a char variable. A correct declaration is:
char grade = 'B'; //Line 2
Variable declaration in Line 3 is incorrect because the left side of the assignment operator must be a variable, and the semicolon at the end of the statement is missing. A correct declaration is:
double num = 28.5; //Line 3
The variable declaration in Line 4 is incorrect because strings are enclosed in double quotation marks. A correct declaration is:
string message = "First C++ course"; //Line 4
The variable declaration in Line 5 is incorrect because the value assigned to age must be an int value. A correct declaration is:
int age = 18; //Line 5
11. a and c are valid
12.
a. int x, y;
x = 25;
y = 18;
b. int temp = 10;
char ch = 'A';
c. x = x + 5;
d. double payRate = 12.5;
e. tempNum = firstNum;
f. temp = x;
x = y; y = temp;
g. cout << x << " " << y << " " << x + 12 / y - 18 << endl;
h. char grade = 'A';
i. int num1, num2, num3, num4;
j. x = static_cast<int>(z + 0.5);
13 a. 9.0 / 5 * C + 32
b. static_cast<int>('+')
c. static_cast<int>(x + 0.5)
d. str = "C++ Programming is exciting"
e. totalInches = 12 * feet + inches
f. i++, ++i, or i = i + 1;
g. v = 4 / 3 * (3.1416 * r * r *r);
h. s = 2* (3.1416 * r * *r) + 2 * (3.1416 * r) * h;
i. a + (b – c) / d * (e * f – g * h)
j. (–b + (b * b – 4 * a * c)) / (2 * a)
14. x = 1
y = 102
z = 15
w = 44
15. x = 101
y = 11
z = 104
w = 159.00
t = 81.50
16.
a. x = 18, y = 5, z = 4
b. 5 * x - y = 85
c. Product of 18 and 4 is 72
d. x - y / z = 17
e. 18 square = 324
17. a. 1000
b. 42.50
c. 1.25
d. 11.00
e. 9
f. 88.25
g. -2.00
18. a. cout << endl; or cout << "\n"; or cout << '\n';
b. cout << "\t";
c. cout << "\"";
19. a and c are correct
20.
a. char grade = '*';
b. doublesalesTax = 0.05;
c. int numOfJuiceBottles = 0;
d. doublebillingAmount = 0.0;
e. doublegpa = 0.0;
21. a. int num1; int num2;
b. cout << "Enter two numbers separated by spaces." << endl;
c. cin >> num1 >> num2;
d. cout << "num1 = " << num1 << ", num2 = " << num2 << ", 2 * num1 – num2 = " << 2 * num1 – num2 << endl;
22. A correct answer is:
#include <iostream>
#include <string>
using namespace std;
const double DECIMAL = 5.50; const string blanks = " "; double PAY_RATE = 10.75;
int main() {
int height, weight; double discount; double billingAmount; double bonus; int hoursWorked = 45; double price;
height = 6; weight = 156;
cout << height << " " << weight << endl; discount = (2 * height + weight) % 10; price = 49.99;
billingAmount = price * (1 - discount) - DECIMAL ; // DECIMAL = 7.55;
cout << price << blanks << "$" << billingAmount << endl; bonus = hoursWorked * PAY_RATE / 50;
cout << "Bonus = " << bonus << endl; return 0; }
23. A correct answer is:
#include <iostream>
using namespace std;
const char STAR = '*'; const int PRIME = 71;
int main() {
int count, sum; double x;
int newNum; //declare newNum
count = 1;
sum = count + PRIME;
x = 25.67; // x = 25.67;
newNum = count * 1 + 2; //newNum = count * ONE + 2; sum++; //(x + sum)++;
sum = sum + count; //sum + count = sum; x = x + sum * count; // x = x + sum * COUNT; sum += 3; //sum += 3 ;
cout << " count = " << count << ", sum = " << sum << ", PRIME = " << PRIME << endl; return 0;
24. A correct answer is:
#include <iostream>
#include <string>
using namespace std;
int main() {
int num1, num2;
string str1;
cout << "Enter a string without any blanks in it : "; cin >> str1;
cout << endl;
cout << "Enter two integers: "; cin >> num1 >> num2;
cout << endl;
cout << str1 << " "
<< "num1 * num2 = " << num1 * num2 << endl; return 0;
25. An identifier must be declared before it can be used.
26. b.
27. a. x += 5;
b. x *= 2 * y
c. totalPay += currentPay;
d. z *= (x + 2);
c. w = w + 2 * z + 4;
d. x = x – (z + y – t);
31. (The user input is shaded.)
firstNum = 62
Enter three numbers: 35 10.5 27
The numbers you entered are 35, 10.5, and 27
z = 33
Enter grade: B
The letter that follows your grade is: C
32. (The user input is shaded.)
Enter last name: Miller
Enter a two digit integer: 34
Enter a decimal number: 62.5
Name: Miller Id: 34
Mystery number: -5.14286
33.
#include <iostream>
#include <string> using namespace std;
const double X = 13.45; const int Y = 18; const char STAR = '*'; int main() { string employeeID; string department; int num; double salary;
cout << "Enter employee ID: "; cin >> employeeID; cout << endl;
cout << "Enter department: "; cin >> department; cout << endl;
cout << "Enter a positive integer less than 80: "; cin >> num; cout << endl;
salary = num * X;
cout << "ID: " << employeeID << endl;
cout << "Department " << department << endl;
cout << "Star: " << STAR << endl;
cout << "Wages: $" << salary << endl;
cout << "X = " << X << endl;
cout << "X + Y = " << X + Y << endl; return 0; }
34. The program requires four inputs in the following order: string decimal_number decimal_number integer
Chapter 3
1. a. true; b. true; c. false; d. false; e. false; f. true; g. false; h. false; i. true; j. false; k. true
2. a. x = 78, y = 86, z = 18, ch = '#'
b. x = 8, y = 86, z = 18, ch = '7'
c. x = 78, y = 86, z = 18, ch = ' '
d. x = 78, y = 6, z = 18, ch = 8
e. x = 8, y = 86, z = 18, ch = '7'
3. a. int1 = 67, int2 = 48, dec1 = 56.5, dec2 = 62.72
b. int1 = 48, int2 = -1, dec1 = 0.5, dec2 = 67
c. int1 = 48, int2 = 62, dec1 = 56.5, dec2 = 67
d. int1 = 56, int2 = 67, dec1 = 0.5, dec2 = 48
e. Input failure: int1 = 56; trying to read the (period) into int2
4. a. x = 38, y = 26, symbol = '2'
b. x = 38, y = 67, symbol = ' '
c. x = 24, y = 38, symbol = '$'
d. x = 67, y = 24, symbol = '3'
e. x = 24, y = 63, symbol = '$'
5. a. Samantha 168.5 46
b. Samantha 0.5 168
c. ** 2.7 45
Input failure: Trying to read S into dec, which is a double variable. The values of dec, num and str are unchanged.
6. a. int1 = 13, int2 = 4, dec = 16.2, ch = '2'
b. int1 = 45, int2 = 36, dec = 9.2, ch = '$'
c. int1 = 16, input failure, trying to read ' . ' into int2, which is an int variable.
7. The function pow calculate xy in a program. That is, pow(x, y)=xy. To use this function the program must include the header file. cmath
8. The function sqrt calculate the square root of a nonnegative real number. To use this function the program must include the header file cmath
9. The manipulator scientific is used to output floating-point numbers in scientific format. To use this function the program must include the header file iomanip
10. iostream
11. The manipulator setw is used to output the value of an expression in a specific number of columns. To use this function the program must include the header file iomanip.
12. 9.00^3.20 = 1131.30
5.0^2.5 = 55.90
sqrt(48.35) = 6.95
static_cast<int>(sqrt(pow(y, 4))) = 10
Length of str = 47
13. iostream
14.
a. num = 34, discard = '#'
b. Input failure. After peeking into the input stream, cin tries to input # into num. However, num is an int variable, so the stream enters the fail state.
c. num = 34, discard = '#'
15. The function getline reads until it reaches the end of the current line. The newline character is also read but not stored in the string variable.
16. cout << setfill('*') << setw(35) << '*' << endl;
17.
a. name = " Christy Miller", height = 5.4
b. name = " ", height = 5.4
18.
a. name = "Christy Miller", height = 5.4
b. name = "Christy Miller", height = 5.4
19.
#include <iostream>
#include <fstream>
using namespace std; int main() { int num1, num2; ifstream infile; ofstream outfile;
infile.open("input.dat"); outfile.open("output.dat");
infile >> num1 >> num2; outfile << "Sum = " << num1 + num2 << endl; infile.close(); outfile.close(); return 0; }
20. Invalid data may cause the input stream to enter the fail state. When an input stream enters the fail state, all further inputs associated with that input stream are ignored. The program continues to execute with whatever values the variables have.
21. fstream
22. infile.open("employee.dat");
23. 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.
24. infile >> acctNumber; infile >> accountType; infile >> balance;
25. a. outfile.open("sales.dat");
b. outfile >> fixed >> showpoint >> setprecision(2);
c. revenue = numOfJuiceBottlesSold * costOfaJuiceBottle;
d outfile >> numOfJuiceBottlesSold >> " " >> costOfaJuiceBottle >> " " >> revenue >> endl;
e. outfile.close();
Chapter 4
1. a. false; b. false; c. false; d. false; e. true; f. false; g. false; h. false; i. false; j. false; k false
2. a. 0 (false) b. 0 (false) c. 1 (true) d. 1 (true)
e. 1 (true) f. 0 (false)
3. a. false; b. true; c. true; d. true;
4. a. false; b. true; c. true; d. false; e. false
5. a. x == z: 0
b. y != z - 9: 0
c. x - y == z + 10: 1
d. !(z < w): 1
e. w - y < x - 2 * z: 0
6. c and e.
7. a. + +
b. 12 / 2 != 4 + 1
c *
13. Omit the semicolon after else. The correct statement is:
if (score >= 60)
cout << "Pass" << endl;
else
cout << "Fail" << endl;
14. a. if (standing == 'F')
cout << << "First Year" << endl; else if ((standing == 'S')
cout << << "Sophomore" << endl; else
cout << << "Junior or Senior" << endl;
b. if (standing == '1' || standing == '2')
cout << << "First Year or Sophomore" << endl; else if ((standing == '3' || standing == '4')
cout << << "Junior or Senior" << endl; else
cout << << "Graduate Student" << endl;
15. The correct code is: if (numOfItemsBought > 10)
shippingCharges = 0.0;
else if (5 <= numOfItemsBought && numOfItemsBought <= 10)
shippingCharges = 3.00 * numOfItemsBought; else if (0 < numOfItemsBought && numOfItemsBought < 5) shippingCharges = 7.00 * numOfItemsBought; 16.
b. 5 15
19 if (sale > 20000)
bonus = 0.10
else if (sale > 10000 && sale <= 20000)
bonus = 0.05; else
bonus = 0.0;
20. if (0 < overSpeed && overSpeed <= 5) fine = 20.00;
else if (5 < overSpeed && overSpeed <= 10) fine = 75.00; else if (10 < overSpeed && overSpeed <= 15) fine = 150.00;
else if (overSpeed > 15)
fine = 150.00 + 20.00 * (overSpeed – 15);
21. a. The output is: Discount = 10%. The semicolon at the end of the if statement terminates the if statement. So the cout statement is not part of the if statement. The cout statement will execute regardless of whether the expression in the if statement evaluates to true or false
b. The output is: Discount = 10% The semicolon at the end of the if statement terminates the if statement. So the cout statement is not part of the if statement. The cout statement will execute regardless of whether the expression in the if statement evaluates to true or false.
22 a. (i) The output is: Grade is C. The value of score after the if statement executes is 70
(ii) The output is: Grade is C. The value of score after the if statement executes is 70
b. (i) No output. The value of score after the if statement executes is 80.
(ii) The output is: Grade is C. The value of score after the if statement executes is 70
23
a. (x == y) ? z = x + y : (x + y) / 2;
b. (hours >= 40.0) ? wages = 40 * 7.50 + 1.5 * 7.5 * (hours – 40) : wages = hours * 7.50;
c. (loanAmount >= 200000) ? closingCosts = 10000 : closingCosts = 8000;
24.
a. if (overSpeed > 10) fine = 200; else fine = 75;
b. if (fuel >= 10) drive = 150; else drive = 30;
c. if (bill >= 50.00) tip = 0.20; else tip = 0.10;
25. a. 40.00
b. 40.00
c. 55.00
26. a, c, and d are valid. b is invalid; a case value cannot appear more than once and there should be a colon after a case value. 27
30. A correct code is:
#include <iostream> using namespace std; int main() { int num1, num2; bool found = false;
cout << "Enter two integers: "; cin >> num1 >> num2; cout << endl;
found = (num1 > num2);
if (found) switch (num1 % num2)
case 0: num2 = num1 / 2; break;
case 1: num1 = num2 / 2; break;
default:
num1 = num1 / num2; num2 = num1 * num2; }
else {
num1 = num1 - num2; num2 = (num1 + num2) / 10; }
cout << num1 << " " << num2 << endl; return 0; }
a. 1 8
b. -5 0
31.
#include <iostream>
using namespace std; const int SECRET = 5;
int main() {
int x, y, w, z;
z = 9;
if (z > 10) {
x = 12; y = 5;
w = x + y + SECRET; } else {
x = 12; y = 4;
w = x + y + SECRET; }
cout << "w = " << w << endl; return 0; }
#include <iostream>
#include <cmath> using namespace std;
int main()
double firstNum, secondNum;
cout << "Enter two nonzero numbers: "; cin >> firstNum >> secondNum; cout << endl;
if (firstNum == 0 || firstNum < 0 || secondNum == 0 || secondNum < 0)
cout << "Both numbers must be positive." << endl; else if (firstNum == secondNum)
cout << firstNum + secondNum << endl; else if (firstNum <= 2)
cout << pow(secondNum, firstNum) << endl; else
cout << firstNum * secondNum << endl;
return 0;
switch (classStanding) {
case 'f': dues = 150.00; break;
case 's': if (gpa >= 3.75)
dues = 75.00; else
dues = 120.00; break;
case 'j': if (gpa >= 3.75) dues = 50.00; else dues = 100.00; break;
case 'n': if (gpa >= 3.75)
dues = 25.00; else dues = 75.00; break;
default:
cout << "Invalid class standing code." << endl; }
34. Suppose that we have the following variables:
double billingAmount; double payment; //payment made by the customer double credit; //credit for the next bill
double penalty; //penalty to be added the next month’s bill double balance; //unpaid balance
double paymentPercent; //percent of the billing amount paid
The following algorithm determines the credit or penalty, and the unpaid balance.
1. Prompt the user to enter the billing amount.
2. Input the billing amount into the variable billingAmount.
3. Prompt the user to input the payment.
4. Input the payment into the variable payment.
5. Determine the unpaid balance using the formula: balance = billingAmount - payment;
6. Determine the percent of the billing amount made by the customer:
if (billingAmount != 0.0) paymentPercent = payment / billingAmount; else
paymentPercent = 0.0;
7. Determine the credit or the penalty, and the unpaid balance including penalty, if any, using the following if/else statement.
if (paymentPercent == 1.0)
{ credit = billingAmount * 0.01; if (credit > 10.00) credit = 10.00; } else
if (paymentPercent >= 0.50) penalty = balance * 0.05; else if (paymentPercent >= 0.20 && paymentPercent < 0.50) penalty = balance * 0.10; else penalty = balance * 0.20; balance = balance + penalty; }
Chapter 5
1. a. true; b. false; c. true; d. false; e. true; f. true; g. true; h. false ; i. false; j. true
2. i = 5 and temp = 48
3 40
4. 1 3 5 7
5. if ch > 'Z' or ch < 'A'
6. Sum = 90
7. Sum = 22
8. Sum = 190
9. temp = 0
10. int count = 0; int sum = 0; int num; while (count < 20) { cin >> num; sum = sum + num; count++;
13. Replace the while loop statement with the following: while (response == 'Y' || response == 'y')
Replace the cout statement:
cout << num1 << " + " << num2 << " = " << (num1 - num2) << endl;
with the following:
cout << num1 << " + " << num2 << " = " << (num1 + num2) << endl;
18.
a. Counter controlled loop.
b. Sentinel controlled loop.
c. EOF controlled loop.
19. Loop control variable: j
The initialization statement: j = 1;
Loop condition: j <= 10;
Update statement: j++
The statement that updates the value of s: s = s + j * (j – 1);
20. 25 600
21 num = 485, y = 15
22 a. ii
b. iii
c. ii
23.
a. *
b. infinite loop
c. infinite loop
d. ****
e. ******
f. ***
24 sum = 0;
for (i = 0; i <= 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) sum = sum + i;
25. The relationship between x and y is: 3y = x
Output: x = 19683, y = 10
c. while
d. while
30. There is more than one answer. One solution is:
#include <iostream>
using namespace std; const int SECRET = 111; int main() { int num1, num2; double x = 0, y = 0; int count;
cout << "Enter two integers: "; cin >> num1 >> num2; cout << endl;
for (count = 1; count > SECRET; ++count) { x = (num1 + num2) / 2.0; y = (num1 - num2) % 2; num1 = num1 + num2; num2 = num2 * (count - SECRET - 1); }
cout << num1 << " " << num2 << " " << x / 5 << " " << (y / 7) << endl; return 0;
31. In a pretest loop, the loop condition is evaluated before executing the body of the loop. In a posttest loop, the loop condition is evaluated after executing the body of the loop. A posttest loop executes at least once, while a pretest loop may not execute at all.
32. a. The loop is executed 5 times; Output: 55 50
b. The loop is executed 4 times; Output: 80 80
c. The loop is executed 1 time; Output: 7 20
d. The loop is executed 3 times; Output: 35 35
e. The loop is executed 3 times; Output: 40 30
f. The loop is executed 0 times; Output: 5 30
33. int num; do
cout << "Enter a number less than 20 or greater than 75: "; cin >> num;
while (20 <= num && num <= 75);
34. int i, value = 0; for (i = 0; i <= 20; i++)
if (i % 2 == 0 && i <= 10)
value = value + i * i;
else if (i % 2 == 0 && i > 10)
value = value + i;
else
value = value - i;
cout << "value = " << value << endl;
The output is: value = 200
35 int i = 0, value = 0; do
if (i % 2 == 0 && i <= 10)
value = value + i * i;
else if (i % 2 == 0 && i > 10)
value = value + i;
else
value = value - i; i = i + 1;
while (i <= 20);
cout << "value = " << value << endl;
The output is: value = 200
36. 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);
37. cin >> number; while (number != -1)
total = total + number; cin >> number;
cout << endl;
cout << total << endl;
38. cin >> number;
while (number != -1)
{
total = total + number; cin >> number;
39.
cout << endl;
cout << total << endl;
a. number = 1;
while (number <= 10) {
cout << setw(3) << number; number++;
b. number = 1; do
cout << setw(3) << number; number++; }
while (number <= 10);
40.
a. int value = 3; int i = 1;
while (i < 5)
value = value * (i + 1) + i; i++;
cout << "value = " << value << endl;
b. int value = 3; int i = 1; do { value = value * (i + 1) + i; i++;
while (i < 5);
cout << "value = " << value << endl;
41.
a. 36 94 260
b. 4 20
c. 30
d. 98 250
1234567654321
123456787654321
12345678987654321
Chapter 6
1. a. false; b. true; c. true; d. true; e. false; f. false; g. true; h. false; i. true; j. true; k. false; l. false;
4. a. pow(9.2, 4.0) b. sqrt(5 * x - 3 * x * y)
pow(a + b, 1/3.0) d. (-b + sqrt(b * b – 4 * a *
e. fabs(3 * x * x - 2 * y)
5. a and b
/ (2 * a)
7. a, b, c, d, e are valid. In f, the second argument in the function call is missing. In g and h, the function call requires one more argument.
8. a. 5
b. 3
c. 40 10
d. 8
9 a. 2; double
b. 3; int
c. 3; string
d. 2; char
e. The function third requires 4 actual parameters. The type and the order of these parameters is: string, string, int, double
f. cout << first(2.5, 7.8) << endl;
g. cout << grade(82.50, 92.50) << endl;
h. cout << third("John", "Blair", 26, 132.5) << endl;
10
. In a C++ program, typically the function main appears before any other user-defined function. The compiler compiles the program sequentially from beginning to end. Now the function main contains calls to user-defined functions. So to correctly translate each function call, the user-defined function prototypes appears before any function definition. Because function prototypes appear before any functiondefinition, the compilertranslates these first. Thecompiler can thencorrectly translate afunction call
11 bool isWhitespace (char ch) { if (isspace(ch)) return true; else return false; }
12. a. 4.00
b. 74.00
c. 92.63
13 a. (i) 72 (ii) -200
b. The function computes mn, where m and n are the arguments of the function.
14. bool funcEx14(double x, double y, double z) { if (floor(x * y) == floor(z)) return true; else return false; }
15. a. 385
b. This function computes 1+4+9+16+25+36+49+64+81+100
16 7
17 double funcEx17(double x, double y) { return pow(x, y) + pow(y, x); }
18. a. -120
b. 37
c. 6
d. 0
19. a. In a void function, a return statement is used without any value such as return;
b. In a void function, a return statement is used to exit the function early.
20.
a.
Function prototype: void func(int, int, double&, char&); //Line 6
Function heading: int main() //Line 7
void func(int speed, int time, //Line 19 double& distance, char& c) //Line 20
Function body:
(function main): starts at Line 8 and ends at Line 18
(function func): starts at Line 21 and ends at Line 26
Function definitions:
(function main): starts at Line 7 and ends at Line 16
b.
(function func): starts at Line 19 and ends at Line 26
Function call: Statements in Lines 13 and 15 func(s, t, d, ch); //Line 13 func(75, 8, d, ch); //Line 15
Formal parameters (function func): speed, time, distance, c
Actual parameters: s, t, d, ch (in Line 13) 75, 8, d, ch (in Line 15)
c.
d.
Value parameters (function func): speed, time
Reference parameters (function func): distance, c
Local variables (function main): s, t, d, ch (function func): num
Global variable: temp
e. Named constant: RATE, STAR
21.
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.
22.
a. Take Programming I.
b. TakeProgramming II.
c. TakeInvalid input. You must enter a 1 or 2
d. TakeInvalid input. You must enter a 1 or 2
23. void funcEx23(int num)
if (num % 2 == 0)
cout << 2 * num << endl; else
cout << 5 * num << endl;
24 void sumAvg(double x, double y, double z, double& sum, double & avg, string& result)
sum = x + y + z; avg = sum / 3;
if (avg >= 70) result = "Pass"; else result = "Fail";
25. void initialize(int& x, double& y, string& str)
x = 0; y = 0; str = "";
26 void sumAvgResult(int n, int m, int& sum, double& avg) {
int count = 0;
sum = 0;
if (n >= m)
{ count = n - m + 1;
for (int i = m; i <= n; i++)
sum = sum + i;
} else { count = m - n + 1;
for (int i = n; i <= m; i++)
sum = sum + i; }
avg = static_cast<double>(sum) / count; //count != 0
29. #include <iostream> using namespace std; int secret(int, int); void func(int x, int& y); int main()
int num1, num2;
1 num1 = 6;
2__ cout << "Enter a positive integer: ";
__3__ cin >> num2;
__4 cout << endl;
__8__ cout << secret(num1, num2) << endl;
__9 num2 = num2 – num1;
_10 cout << num1 << " " << num2 << endl;
_15 func(num2, num1);
_16__ cout << num1 << " " << num2 << endl;
_17__ return 0;
int secret(int a, int b)
int d;
__5 d = a + b;
__6 b = a * d;
__7 return b;
void func (int x, int& y)
int val1, val2;
_11__ val1 = x + y;
12__ val2 = x * y;
_13__ y = val1 + val2;
_14__ cout << val1 << " " << val2 << endl;
If the input is 10, the output is:
30
a. The user input is shaded.
Enter two numbers: 3 5
z = 8.00, one = 11.00, two = 5.00
z = 16.00, one = 11.00, two = 21.00
b. The user input is shaded.
Enter two numbers: 4 11
z = 15.00, one = 19.00, two = 11.00
z = 30.00, one = 19.00, two = 41.00
c One possible answer is: (The user input is shaded.)
Enter two numbers: 10 10
z = 20.00, one = 30.00, two = 10.00
z = 40.00, one = 30.00, two = 50.00
31 void trackVar(double& x, double y, double& z)
z = floor(x) + ceil(y);
x = x + z;
y = y - z;
Sample Run:
Line 9: In main: num1 = 10, num2 = 20
Line 19: In funOne: a = 10, x = 12, and z = 22
Line 21: In funOne: a = 10, x = 17, and z = 22
Line 23: In funOne: a = 18, x = 17, and z = 22
Line 11: In main after funOne: num1 = 18, num2 = 20
Before the statement in Line 9 executes, the variables are:
Line 9 produces the following line of output:
Line 9: In main: num1 = 10, num2 = 20
The statement in Line 10 calls the function funOne; control transfers to the function funOne. Before the statement in Line 18 executes, the variables are:
After the statement in Line 18 executes, the variables are:
Line 19 produces the following output:
Line 19: In funOne: a = 10, x = 12, and z = 22
After the statement in Line 20 executes, the variables are:
Line 21 produces the following output:
Line 21: In funOne: a = 10, x = 17, and z = 22
After the statement in Line 22 executes, the variables are:
Line 23 produces the following output:
Line 23: In funOne: a = 18, x = 17, and z = 22
After the statement in Line 23 executes, control goes back to the function main at Line 11. Before the statement in Line 11 executes, the variables are:
Line 11 produces the following output:
Line 11: In main after funOne: num1 = 18, num2 = 20
35 stVar = 3, u = 3, x = 2
stVar = 9, u = 3, x = 3
stVar = 18, u = 3, x = 4
stVar = 36, u = 3, x = 5
36. The signature of a function consists of the function name and its formal parameter list.
37. a, b, and d are correct.
38. a. 69, 71.50
b. 51, 53.50
c. 53, 60.50
d. 51, 57.50
Chapter 7
2. a. enum flowerType {ROSE, DAISY, CARNATION, FREESIA, GARDENIA, ALLIUM,TULIP, IRIS, SUNFLOWER, LILAC, ORCHID};
b. flowerType flower;
c. flower = TULIP;
d. flower = static cast<flowerType>(flower + 1);
e. flower = static cast<flowerType>(flower - 1) ;
f. switch(flower)
{
case ROSE: cout << "Rose"; break;
case DAISY: cout << "Daisy"; break;
case CARNATION: cout << "Carnation"; break;
case FREESIA: cout << "Freesia"; break;
case GARDENIA: cout << "Gardenia"; break;
case ALLIUM: cout << "Allium";
case TULIP: cout << "Tulip"; break;
case IRIS: cout << "Iris"; break;
case SUNFLOWER: cout << "Sunflower"; break;
case LILAC: cout << "Lilac"; break;
case ORCHID: cout << "Orchid";
}
g string str; cin >> str;
if (str == "Rose")
flower = ROSE; else if (str == "Daisy")
flower = DAISY; else if (str == "Carnation")
flower == CARNATION; else if (str == "Freesia")
flower = FREESIA; else if (str == "Gardenia")
flower = GARDENIA; else if (str == "Allium")
flower = ALLIUM; else if (str == "Tulip")
flower = TULIP; else if (str == "Iris")
flower = IRIS; else if (str == "sunflower")
flower = SUNFLOWER; else if (str == "Lilac")
flower = LILAC; else if (str == "Orchid")
flower = ORCHID; else
cout << "Invalid flower name." << endl;
3. Only a and c are valid.
4. a. 4
b. GRAPE
c. MANGO
d. 1 (true)
e. No output. Syntax error. The expression fruit++ should be static_cast<fruitType>(fruit + 1)
5.
flowerType readIn() { string str; flowerType flower = 0; cin >> str; if (str == "Rose")
flower = ROSE; else if (str == "Daisy")
flower = DAISY; else if (str == "Carnation")
flower == CARNATION; else if (str == "Freesia")
flower = FREESIA; else if (str == "Gardenia")
flower = GARDENIA; else if (str == "Allium")
flower = ALLIUM;
6.
else if (str == "Tulip")
flower = TULIP; else if (str == "Iris")
flower = IRIS; else if (str == "sunflower")
flower = SUNFLOWER; else if (str == "Lilac")
bir flower d == LILAC; else if (str == "Orchid")
flower = ORCHID;
else
cout << "Invalid flower name." << endl; return flower; }
void printflowerName(flowerType flower) {
switch(flower) {
case ROSE: cout << "Rose"; break;
case DAISY: cout << "Daisy"; break;
case CARNATION: cout << "Carnation"; break;
case FREESIA: cout << "Freesia"; break;
case GARDENIA:
cout << "Gardenia"; break;
case ALLIUM: cout << "Allium";
case TULIP: cout << "Tulip"; break;
case IRIS: cout << "Iris"; break;
case SUNFLOWER: cout << "Sunflower"; break;
case LILAC: cout << "Lilac"; break;
case ORCHID: cout << "Orchid";
switch
printflowerName
7. Because there is no name for an anonymous type, you cannot pass an anonymous type as a parameter to a function and a function cannot return an anonymous type value. Also, values used in one
anonymous type can be used in another anonymous type, but variables of those types are treated differently.
8. enum quadrilateralType {SQUARE, RECTANGLE, RHOMBUS, TRAPEZIOD, PARALLELOGRAM, QUADRILATERAL, KITE} quadrilateral;
9. The statement in Line1 1 and 2 should be: #include <iostream> //Line 1 using namespace std; //Line 2
10. The program does not use the statement: using namespace std; There are several errors in this code. The correct code is:
#include <iostream> //Line 1
#include <string> //Line 2
int main() //Line 3 { //Line 4 std::string str; //Line 5 std::cin >> str; //Line 6 std::cout << str << std::endl; //Line 7 return 0; //Line 8 } //Line 9 //Line 9
11. The statement in Line 2 should be: using namespace std; //Line 2
12 Replace the statement in Line 2 with the following: using namespace mySpace //Line 2
Replace the statement in Line 12 with the following: mySpace::x = static_cast<int>(num); //Line 12 Also, either include the following statement before the function main: using namespace mySpace; or replace the statements in Lines 11, 13, and 14 with the following statements: num = 2 * mySpace::PRIZE; //Line 11 cout << mySpace::PRIZE << " " << mySpace::x << " " //Line 13 << num << endl; //Line 14
13. 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.
14. The statement in Line 2 should be: #include <cmath> In Line 3, nameSpace should be namespace
Statement in Line 4 should be: int main() //Line 4
15
a. Sammer Vucation
b. Temperary Projoct
c. Nocial Setwork
Chapter 8
1. a. true; b. true; c. true; d. false; e. false; f. false; g. false; h. false; i. true; j. false; k. false; l. false
2. a. currentBalance
b. 91
c. double
d. 0 to 90
e. first = 0, middle = 45, last = 90
3. a. This declaration is correct.
b. Array size must be positive. A correct answer is: int testScores[10];
c. This declaration is correct.
d. Array size must be a positive integer not a range. A correct answer is: int list100[100];
e. gpa is an array of size 50. The expression [50] should be after gpa. The correct statement is: double gpa[50];
f. LENGTH must be declared as integral, such as int A correct statement is: const int LENGTH = 26;
g. This declaration is correct.
4. a. Valid
b. Invalid. The data type should be string.
c. Invalid. The size of the array gpa must be specified as a positive integer.
d. Invalid. Incorrect syntax and array size. A correct declaration is: double ratings[50];
e. Valid.
f. Valid.
g. Invalid. The size of array sales must be a positive integer. The expression 100 - 2 * MAX_SIZE = 100 - 2 * 50 = 0
5. 0 to 64. first = 0, middle = 32, last = 64
6. a. int alpha[50];
b. for (int i = 0; i < 50; i++) alpha[i] = -1;
c. cout << alpha[0] << endl;
d. alpha[24] = 62;
e. alpha[9] = alpha[49] + 10.
f. for (int i = 0; i < 50; i++)
if (i % 2 == 0 || i % 3 == 0)
cout << alpha[i] << " "; cout << endl;
g. cout << alpha[49] << endl;
h. for (int i = 0; i < 50; i++) {
cout << alpha[i] << " ";
if ( (i + 1) % 15) cout << endl; }
cout << endl;
i. for (int i = 0; i < 50; i = i + 2) alpha[i] = alpha[i] + 1;
j. int diffAlpha[49];
for (int i = 0; i < 49; i++) diffAlpha[i] = alpha[i] - alpha[i - 1];
11. int myList[10];
for (int i = 0; i < 10; i++) myList[i] = i;
12. int intList[5];
for (int i = 0; i < 5; i++) cin >> intList[i];
for (int i = 0; i < 5; i++) cout << intList[i] << " "; cout << endl;
13. If array index is less than 0 or greater than arraySize – 1, we say that the array index is out-of bounds. C++ does not check for array indices within bound.
14. The output of the code is: points[2] and points[3] are out of order. points[7] and points[8] are out of order.
The correct code is:
for (int i = 0; i < 10; i++) if (points[i + 1] > points[i]) cout << "points[" << i << "] and points[" << (i + 1) << "] are out of order." << endl;
b. int weights[7] = {120, 125, 137, 140, 150, 180, 210}; or int weights[] = {120, 125, 137, 140, 150, 180, 210};
c. char specialSymbols[] = {'$', '#', '%', '@', '&', '! ' , '^'};
d. string seasons[4] = {"fall" , "winter" , "spring" , "summer"}; or string seasons[] = {"fall" , "winter" , "spring" , "summer"};
16. a. Valid. The size of list is 4.
b. Valid. The size of x is 10.
c. Invalid. The size of y is 4. However, the number of array initializers is 5, excedding the size of the array.
d. Valid.
e. Invalid. When initializing an array during declaration, all elements that follow the first unspecified element must be unspecified.
f. Valid.
17. alpha[0] = 3, alpha [1] = 12, alpha [2] = -25, alpha [3] = 72, alpha [4] = 0
18. a. for (int i = 0; i < 6; i++) cout << list[i] << " "; cout << endl;
b. for (int i = 0; i < 5; i++) list[i] = list[i] – 3 * list[i + 1]; 19.
21. a. Correct.
b. Correct.
c. Incorrect. None of the formal parameters list and sList are of type double while the actual parameter unitPrice is of type double. So there will be mismatch data type error.
d. Incorrect. The size of the array ids is 50, so the call should be printList(ids, 50);
e. Correct.
22. a. Valid.