Programming Group Assibnment
Programming Group Assibnment
Program
Intro. Computer sceience
and programing 1
4.11 (Correct the Code Errors) Identif y and correct the error(s) in each of the following:
a) if (age >= 65 );
else
Corrected
else
b) if ( age >= 65 )
else;
Corrected
else
c) unsigned int x = 1;
while ( x <= 10 ){
total += x;
1
++x;
Corrected
unsigned int x = 1;
while ( x <= 10 ){
total += x;
++x;
total += x;
++x;
Corrected
total += x;
++x;}
e) while ( y > 0 ){
++y;
Corrected
--y;
2
4.12 (What Does this Program Do?) What does the following program print ?
#include <iostream>
int main() {
y = x * x; // perform calculation
} // end while
} // end main
1. Loops from x = 1 to x = 10
2. In each loop:
3. Finally, it print s the total sum of all the squares from 1² to 10².
plaint ext
3
Copy code
16
25
36
49
64
81
100
Total is 385
4.13 (Gas Mileage) Drivers are concerned with the mileage obtained by their automobiles.
One driver has kept track of several trips by recording miles driven and gallons used for each
trip. Develop a C++ program that uses a while statement to input the miles driven and gallons
used for each trip. The program should calculate and display the miles per gallon obtained for
each trip and print the combined miles per gallon obtained for all tankfuls up to this point .
4
MPG this trip: 24.000000
#include <iostream>
int main() {
double totalMiles = 0;
double totalGallons = 0;
totalMiles += miles;
totalGallons += gallons;
return 0;
5
4.13 (Gas Mileage) Drivers are concerned with the mileage obtained by their automobiles.
One driver has kept track of several trips by recording miles driven and gallons used for each
trip. Develop a C++ program that uses a while statement to input the miles driven and gallons
used for each trip. The program should calculate and display the miles per gallon obtained for
each trip and print the combined miles per gallon obtained for all tankfuls up to this point .
#include <iostream>
int main() {
6
while (miles != -1) {
totalMiles += miles;
totalGallons += gallons;
return 0;
4.14 (Credit Limits) Develop a C++ program that will determine whether a department-store
customer has exceeded the credit limit on a charge account. For each customer, the following
factsare available:
The program should use a while statement to input each of these facts, calculate the new
balance(= beginning balance + charges – credits) and determine whether the new balance
exceeds the customer’s credit limit. For those customers whose credit limit is exceeded, the
7
program should display the customer’s account number, credit limit, new balance and the
message “Credit Limit Exceeded.”
Account: 100
Balance: 5894.78
#include <iostream>
int main() {
int accountNumber;
8
double beginningBalance, totalCharges, totalCredits, creditLimit, newBalance;
return 0;
9
4.15 (Sales Commission Calculator) A large company pays its salespeople on a commission
basis.The salespeople each receive $200 per week plus 9% of their gross sales for that week.
For example,a salesperson who sells $5000 worth of chemicals in a week receives $200 plus
9% of $5000, or a total of $650. Develop a C++ program that uses a while statement to input
each salesperson’s gross sales for last week and calculates and displays that salesperson’s
earnings. Process one salesperson’s figures at a time.
#include <iostream>
#include <iomanip>
int main() {
double grossSales;
10
while (grossSales != -1) {
return 0;
4.16 (Salary Calculator) Develop a C++ program that uses a while statement to determine the
gross pay for each of several employees. The company pays “straight time” for the first 40
hours worked by each employee and pays “time-and-a-half” for all hours worked in excess of
40 hours. You are given a list of the employees of the company, the number of hours each
employee worked last week and the hourly rate of each employee. Your program should input
this information for each employee and should determine and display the employee’s gross
pay.
Salary is $390.00
Salary is $400.00
Salary is $415.00
11
Answer : C++ Program
#include <iostream>
#include <iomanip>
int main() {
} else {
return 0;
12
4.17 (Find the Largest) The process of finding the largest number (i.e., the maximum of a
group of numbers) is used frequently in computer applications. For example, a program that
determines the winner of a sales contest inputs the number of units sold by each salesperson.
The salesperson who sells the most units wins the contest. Write a C++ program that uses a
while statement to determine and print the largest number of 10 numbers input by the user.
Your program should use three variables, as follows:
counter: A counter to count to 10 (i.e., to keep track of how many numbers have
been input and to determine when all 10 numbers have been processed).
#include <iostream>
int main() {
int counter = 1;
int number;
int largest;
largest = number;
counter++;
13
if (number > largest) {
largest = number;
cout << “The largest number is: “ << largest << endl;
return 0;
4.18 (Tabular Output) Write a C++ program that uses a while statement and the tab escape
sequence\t to print the following table of values:
1 10 100 1000
2 20 200 2000
3 30 300 3000
4 40 400 4000
5 50 500 5000
#include <iostream>
int main() {
int N = 1;
while (N <= 5) {
cout << N << “\t” << 10 * N << “\t” << 100 * N << “\t” << 1000 * N << “\n”;
N++; }
return 0;
14
4.19 (Find the Two Largest Numbers) Using an approach similar to that in Exercise
4.17, find the two largest values among the 10 numbers. [Note: You must input each
number only once.]
#include <iostream>
int main() {
int counter = 1;
int number;
largest = number;
secondLargest = number;
counter++;
secondLargest = largest;
largest = number;
cout << “The largest number is: “ << largest << endl;
cout << “The second largest number is: “ << secondLargest << endl;
return 0;
4.20 (Validating User Input) The examination-results program of Fig. 4.16 assumes that any
value input by the user that’s not a 1 must be a 2. Modif y the application to validate its
inputs. On any input, if the value entered is other than 1 or 2, keep looping until the user
enters a correct value.
#include <iostream>
int main() {
int answer;
return 0;
16
4.21 (What Does this Program Do?) What does the following program print ?
#include <iostream>
int main(){
} // end while
} // end main
****
++++++++
****
++++++++
****
++++++++
****
++++++++
****
++++++++
17
4.22 (What Does this Program Do?) What does the following program print ?
#include <iostream>
int main() {
} // end main
>>>>>>>>>>
<<<<<<<<<<
>>>>>>>>>>
<<<<<<<<<<
18
>>>>>>>>>>
<<<<<<<<<<
>>>>>>>>>>
<<<<<<<<<<
>>>>>>>>>>
<<<<<<<<<<
4.23 (Dangling-else Problem) State the output for each of the following when x is 9 and y is 11
and when x is 11 and y is 9. The compiler ignores the indentation in a C++ program. The C++
compiler always associates an else with the previous if unless told to do otherwise by the
placement of braces {}. On first glance, you may not be sure which if and else match, so this is
referred to as the “dangling-else” problem. We eliminated the indentation from the following
code to make the problem more challenging. [Hint : Apply indentation conventions you’ve
learned.]
a) if ( x < 10 )
if ( y > 10 )
else
if ( x < 10 )
if ( y > 10 )
else
b) if ( x < 10 ){
if ( y > 10 )
19
cout << “*****” << endl;
else
if ( x < 10 ) {
if ( y > 10 )
cout << “*****” << endl;
}
else {
cout << “#####” << endl;
cout << “$$$$$” << endl;
}
4.24 (Another Dangling-else Problem) Modif y the following code to produce the output shown.
Use proper indentation techniques. You must not make any changes other than inserting
braces. The compiler ignores indentation in a C++ program. We eliminated the indentation from
the following code to make the problem more challenging. [Note: It’s possible that no modif
ication is necessary.]
if ( y == 8 )
if ( x == 5 )
else
20
a) Assuming x = 5 and y = 8, the following output is produced.
@@@@@
$$$$$
&&&&&
Answer
if ( y == 8 ) {
if ( x == 5 )
Answer
if ( y == 8 ) {
if ( x == 5 )
cout << “@@@@@” << endl;
else {
cout << “#####” << endl;
cout << “$$$$$” << endl;
cout << “&&&&&” << endl;
}
}
c) Assuming x = 5 and y = 8, the following output is produced.
@@@@@
&&&&&
Answer
if ( y == 8 )
if ( x == 5 )
21
d) Assuming x = 5 and y = 7, the following output is produced. [Note: The last
three output statements after the else are all part of a block.]
#####
$$$$$
&&&&&
Answer
if ( y == 8 ) {
if ( x == 5 )
else {
4.25 (Square of Asterisks) Write a program that reads in the size of the side of a square then
print s a hollow square of that size out of asterisks and blanks. Your program should work for
squares of all side sizes between 1 and 20. For example, if your program reads a size of 5, it
should print .
*****
* *
* *
* *
*****
Answer
#include <iostream>
using namespace std;
int main() {
22
int size;
return 0;
}
4.29 (Multiples of 2 with an Infinite Loop) Write a program that print s the powers of the int
eger
2, namely 2, 4, 8, 16, 32, 64, etc. Your while loop should not terminate (i.e., you should create
an infinite loop). To do this, simply use the keyword true as the expression for the while
statement.
What happens when you run this program?
23
Answer
#include <iostream>
using namespace std;
int main() {
unsigned long long power = 2;
while (true) {
cout << power << endl;
power *= 2; // multiply by 2 for next power
}
return 0; // this will never be reached
}
4.30 (Calculating a Circle’s Diameter, Circumference and Area) Write a program that reads the
radius of a circle (as a double value) and computes and print s the diameter, the
circumference and the area. Use the value 3.14159 for π.
Answer
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
const double pi = 3.14159;
double radius;
cout << “Enter the radius of the circle: “;
cin >> radius;
24
}
4.31 What’s wrong with the following statement? Provide the correct statement to
accomplish what the programmer was probably trying to do.
cout << ++( x + y );
Answer
cout << (++x + y);
4.32 (Sides of a Triangle) Write a program that reads three nonzero double values and
determines and print s whether they could represent the sides of a triangle.
Answer
#include <iostream>
using namespace std;
int main() {
double a, b, c;
return 0;
}
25
4.33 (Sides of a Right Triangle) Write a program that reads three nonzero int egers and
determines and print s whether they’re the sides of a right triangle.
Answer
#include <iostream>
#include <algorithm> // for sort
using namespace std;
int main() {
int a, b, c;
26
a) Write a program that reads a nonnegative int eger and computes and print s its
factorial.
Answer
#include <iostream>
using namespace std;
int main() {
unsigned int n; // nonnegative int eger
unsigned long long fact = 1; // to hold large factorials
b) Write a program that estimates the value of the mathematical constant e by using the
formula:
Prompt the user for the desired accuracy of e (i.e., the number of terms in the
summation).
Answer
#include <iostream>
using namespace std;
int main() {
int n;
cout << “Enter the number of terms to estimate e: “;
cin >> n;
27
double e = 1.0; // Start with 1 (0! = 1)
double factorial = 1.0; // Store current factorial
int i = 1;
while (i <= n) {
factorial *= i; // i!
e += 1.0 / factorial;
++i;
}
cout << “Estimated value of e using “ << n << “ terms is: “ << e << endl;
return 0;
}
Prompt the user for the desired accuracy of e (i.e., the number of terms in the summation).
Answer
#include <iostream>
using namespace std;
int main() {
double x; // exponent
int n; // number of terms
cout << “Enter the value of x: “;
cin >> x;
cout << “Enter the number of terms to estimate e^x: “;
cin >> n;
double result = 1.0; // Start with the 0th term (1)
double term = 1.0; // Current term value (x^i / i!)
int i = 1;
while (i <= n) {
term = term * x / i; // Efficient way to compute x^i / i! from previous term
result += term;
++i;
}
cout << “Estimated value of e^” << x << “ using “ << n << “ terms is: “ << result << endl;
return 0;
28
}
5.4 (Find the Code Errors) Find the error(s), if any, in each of the following:
a) For ( unsigned int x = 100, x >= 1, ++x )
cout << x << endl;
Answer
for (unsigned int x = 100; x >= 1; --x)
cout << x << endl;
b) The following code should print whether int eger value is odd or even:
switch ( value % 2 )
{
case 0:
cout << “Even int eger” << endl;
case 1:
cout << “Odd int eger” << endl;
}
Corrected
switch ( value % 2 )
{
case 0:
cout << “Even int eger” << endl;
break;
case 1:
cout << “Odd int eger” << endl;
break;
}
c) The following code should output the odd int egers from 19 to 1:
for ( unsigned int x = 19; x >= 1; x += 2 )
cout << x << endl;
corrected
29
d) The following code should output the even int egers from 2 to 100:
unsigned int counter = 2;
do
{
cout << counter << endl;
counter += 2;
} While ( counter < 100 );
Corrected
#include <iostream>
using namespace std;
int main() {
unsigned int counter = 2;
do {
cout << counter << endl;
counter += 2;
} while (counter <= 100);
return 0;
}
5.5 (Summing Int egers) Write a program that uses a for statement to sum a sequence of int
egers.Assume that the first int eger read specif ies the number of values remaining to be
entered. Your program should read only one value per input statement. A typical input
sequence might be
5 100 200 300 400 500
where the 5 indicates that the subsequent 5 values are to be summed.
Answer
#include <iostream>
using namespace std;
int main() {
int count, number, sum = 0;
30
cout << “Enter the number of values to sum: “;
cin >> count;
5.6 (Averaging Int egers) Write a program that uses a for statement to calculate the average
of
several int egers. Assume the last value read is the sentinel 9999. For example, the sequence
10 8 11
Answer
#include <iostream>
using namespace std;
int main() {
int number;
int total = 0;
int count = 0;
if (number == 9999)
break;
total += number;
count++;
31
}
if (count != 0) {
double average = static_cast<double >(total) / count;
cout << “Average is: “ << average << endl;
} else {
cout << “No numbers were entered.” << endl;
}
return 0;
}
5.7 (What Does This Program Do?) What does the following program do?
int main()
{
unsigned int x; // declare x
unsigned int y; // declare y
Answer
32
@@@@@
@@@@@
@@@@@
5.8 (Find the Smallest Int eger) Write a program that uses a for statement to find the smallest
of several int egers. Assume that the first value read specif ies the number of values
remaining.
Answer
#include <iostream>
using namespace std;
int main() {
cout << “The smallest number is: “ << smallest << endl;
return 0;
}
5.9 (Product of Odd Int egers) Write a program that uses a for statement to calculate and print
33
the product of the odd int egers from 1 to 15.
Answer
#include <iostream>
using namespace std;
int main() {
long long product = 1; // Use long long to avoid overflow
cout << “Product of odd int egers from 1 to 15 is: “ << product << endl;
return 0;
}
5.10 (Factorials) The factorial function is used frequently in probability problems. Using the
definition of factorial in Exercise 4.34, write a program that uses a for statement to evaluate
the factorials of the int egers from 1 to 5. Print the results in tabular format. What dif ficulty
might prevent you from calculating the factorial of 20?
Answer
#include <iostream>
#include <iomanip> // for setw
using namespace std;
int main() {
cout << “Number\tFactorial\n”;
cout << “-----------------\n”;
for (int n = 1; n <= 5; ++n) {
unsigned long long factorial = 1;
34
cout << setw(6) << n << “\t” << factorial << endl;
}
return 0;
}
5.11 (Compound Int erest) Modif y the compound int erest program of Section 5.4 to repeat
its
steps for the int erest rates 5%, 6%, 7%, 8%, 9% and 10%. Use a for statement to vary the int
erest rate.
Answer
#include <iostream>
#include <cmath> // for pow function
#include <iomanip> // for formatting output
int main() {
double principal;
int years;
35
print the following patterns separately, one below the other. Use for loops to generate the
patterns. All asterisks (*) should be print ed by a single statement of the form cout << '*'; (this
causes the
asterisks to print side by side). [Hint : The last two patterns require that each line begin with
an appropriate number of blanks. Extra credit: Combine your code from the four separate
problems int o a single program that print s all four patterns side by side by making clever use
of nested for loops.]
Answer
a) #include <iostream>
using namespace std;
int main() {
int rows = 10;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
cout << “*”;
}
cout << endl;
}
return 0;
}
b) #include <iostream>
using namespace std;
int main() {
int rows = 10;
36
}
cout << endl;
}
return 0;
}
c) #include <iostream>
using namespace std;
int main() {
int rows = 10;
for (int i = 0; i < rows; i++) {
// Print leading spaces
for (int j = 0; j < i; j++) {
cout << “ “;
}
// Print stars
for (int k = 0; k < rows - i; k++) {
cout << “*”;
}
cout << endl;
}
return 0;
}
d) #include <iostream>
int main() {
int rows = 10;
37
cout << endl;
return 0;
}
5.13 (Bar Chart) One int eresting application of computers is drawing graphs and bar charts.
Write a program that reads five numbers (each between 1 and 30). Assume that the user
enters only valid values. For each number that is read, your program should print a line
containing that number of adjacent asterisks. For example, if your program reads the number
7, it should print *******.
Answer
#include <iostream>
using namespace std;
int main() {
const int count = 5;
int numbers[count];
cout << “Enter 5 numbers (each between 1 and 30):” << endl;
// Read 5 numbers
for (int i = 0; i < count; ++i) {
cin >> numbers[i];
}
return 0;
}
38
5.14 (Calculating Total Sales) A mail order house sells five dif ferent products whose retail
prices are: product 1 — $2.98, product 2—$4.50, product 3—$9.98, product 4—$4.49 and
product 5—$6.87. Write a program that reads a series of pairs of numbers as follows:
a) product number
b) quantity sold
Your program should use a switch statement to determine the retail price for each product. Your
program should calculate and display the total retail value of all products sold. Use a sentinel-
controlled loop to determine when the program should stop looping and display the final
results.
Answer
#include <iostream>
using namespace std;
int main() {
int productNumber;
int quantity;
double totalSales = 0.0;
double price = 0.0;
while (true) {
cout << “Product number (1-5, 0 to quit): “;
cin >> productNumber;
if (productNumber == 0)
break;
switch (productNumber) {
case 1:
price = 2.98;
break;
case 2:
price = 4.50;
break;
39
case 3:
price = 9.98;
break;
case 4:
price = 4.49;
break;
case 5:
price = 6.87;
break;
default:
cout << “Invalid product number. Try again.\n”;
continue; // skip the rest of the loop
}
cout << “Total retail value of all products sold: $” << totalSales << endl;
return 0;
}
5.15 (GradeBook Modif ication) Modif y the GradeBook program of Figs. 5.9–5.11 to calculate
the grade-point average. A grade of A is worth 4 point s, B is worth 3 point s, and so on.
Answer
#include <iostream>
using namespace std;
int main() {
char grade;
int totalGrades = 0;
int totalPoint s = 0;
while (true) {
cout << “Enter grade: “;
cin >> grade;
40
// Convert to uppercase to handle lowercase input
grade = toupper(grade);
if (grade == 'Q') {
break; // quit input
}
switch (grade) {
case 'A':
totalPoint s += 4;
totalGrades++;
break;
case 'B':
totalPoint s += 3;
totalGrades++;
break;
case 'C':
totalPoint s += 2;
totalGrades++;
break;
case 'D':
totalPoint s += 1;
totalGrades++;
break;
case 'F':
totalPoint s += 0;
totalGrades++;
break;
default:
cout << “Invalid grade entered. Please enter A, B, C, D, F, or Q to quit.\n”;
}
}
if (totalGrades > 0) {
double gpa = static_cast<double >(totalPoint s) / totalGrades;
cout << “Grade Point Average (GPA): “ << gpa << endl;
} else {
41
cout << “No grades were entered.” << endl;
}
return 0;
}
5.16 (Compound Int erest Calculation) Modif y Fig. 5.6 so it uses only int egers to calculate the
compound int erest. [Hint : Treat all monetary amounts as numbers of pennies. Then “break”
the result int o its dollar and cents portions by using the division and modulus operations.
Insert a period.]
Answer
#include <iostream>
#include <cmath> // for pow if needed (but we will avoid floats)
using namespace std;
int main() {
int principalDollars;
int years;
int int erestRatePercent;
42
long long dollars = amountCents / 100;
int cents = amountCents % 100;
cout << “After “ << years << “ years at “ << int erestRatePercent
<< “% int erest, the investment will be worth $”
<< dollars << “.”;
// Print cents with leading zero if needed
if (cents < 10)
cout << “0”;
cout << cents << endl;
return 0;
}
5.17 (What Print s?) Assume i = 1, j = 2, k = 3 and m = 2. What does each statement print ?
a) cout << ( i == 1 ) << endl;
b) cout << ( j == 3 ) << endl;
c) cout << ( i >= 1 && j < 4 ) << endl;
d) cout << ( m <= 99 && k < m ) << endl;
e) cout << ( j >= i || k == m ) << endl;
f) cout << ( k + m < j || 3 - j >= k ) << endl;
g) cout << ( !m ) << endl;
h) cout << ( !( j - m ) ) << endl;
i) cout << ( !( k > m ) ) << endl;
Answer
Expression Output
a 1
b 0
c 1
d 0
e 1
f 0
g 0
43
Expression Output
h 1
i 0
5.18 (Number Systems Table) Write a program that print s a table of the binary, octal and
hexadecimal equivalents of the decimal numbers in the range 1–256. If you are not familiar
with these number systems, read Appendix D. [Hint : You can use the stream manipulators
dec, oct and hex to display int egers in decimal, octal and hexadecimal formats, respectively.]
Answer
#include <iostream>
#include <bitset> // For binary conversion
#include <iomanip> // For formatting
int main() {
cout << left << setw(10) << “Decimal”
<< setw(12) << “Binary”
<< setw(10) << “Octal”
<< setw(12) << “Hexadecimal” << endl;
44
}
return 0;
}
Print a table that shows the approximate value of π after each of the first 1000 terms of this
series.
Answer
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double pi_over_4 = 0.0;
int sign = 1;
cout << setw(10) << “Term” << setw(20) << “Approximation of Pi” << endl;
cout << “-----------------------------------------” << endl;
cout << setw(10) << term << setw(20) << setprecision(15) << pi_approx << endl;
}
return 0;
}
5.20 (Pythagorean Triples) A right triangle can have sides that are all int egers. A set of three int
eger values for the sides of a right triangle is called a Pythagorean triple. These three sides must
45
satisfy the relationship that the sum of the squares of two of the sides is equal to the square of
the hypotenuse. Find all Pythagorean triples for side1, side2 and hypotenuse all no larger than
500. Use a triple-nested for loop that tries all possibilities. This is an example of brute force
computing. You’ll learn in more advanced computer science courses that there are many int
eresting problems for which there’s no known algorithmic approach other than sheer brute
force.
Answer
#include <iostream>
using namespace std;
int main() {
const int max_side = 500;
cout << “Pythagorean triples (side1, side2, hypotenuse) with sides <= “ << max_side << “:\n”;
return 0;
}
5.21 (Calculating Salaries) A company pays its employees as managers (who receive a fixed
weekly salary), hourly workers (who receive a fixed hourly wage for up to the first 40 hours they
work and “time-and-a-half”—1.5 times their hourly wage—for overtime hours worked),
commission workers (who receive $250 plus 5.7 percent of their gross weekly sales), or
pieceworkers (who receive a fixed amount of money per item for each of the items they
produce—each pieceworker in this company works on only one type of item). Write a program
to compute the weekly pay for each employee. You do not know the number of employees in
advance. Each type of employee has its own pay code: Managers have code 1, hourly workers
46
have code 2, commission workers have code 3 and pieceworkers have code 4. Use a switch to
compute each employee’s pay according to that employee’s paycode. Within the switch, prompt
the user (i.e., the payroll clerk) to enter the appropriate facts your program needs to calculate
each employee’s pay according to that employee’s paycode.
Answer
#include <iostream>
using namespace std;
int main() {
int payCode;
char continueInput = 'y';
switch (payCode) {
case 1: {
// Manager: fixed weekly salary
double salary;
cout << “Enter fixed weekly salary: $”;
cin >> salary;
weeklyPay = salary;
break;
}
case 2: {
// Hourly worker: hourly wage + overtime
double hourlyWage;
double hoursWorked;
cout << “Enter hourly wage: $”;
cin >> hourlyWage;
cout << “Enter hours worked: “;
47
cin >> hoursWorked;
48
}
5.22 (De Morgan’s Laws) In this chapter, we discussed the logical operators &&, || and !. De
Morgan’s laws can sometimes make it more convenient for us to express a logical expression.
These laws state that the expression !( condition1 && condition2 ) is logically equivalent to the
expression ( !condition1 || !condition2 ). Also, the expression !( condition1 || condition2 ) is
logically equivalent to the expression ( !condition1 && !condition2 ). Use De Morgan’s laws to
write equivalent expressions for each of the following, then write a program to show that the
original expression and the new expression in each case are equivalent:
a) !( x < 5 ) && !( y >= 7 )
b) !( a == b ) || !( g != 5 )
c) !( ( x <= 8 ) && ( y > 4 ) )
d) !( ( i > 4 ) || ( j <= 6 ) )
Answer
#include <iostream>
using namespace std;
int main() {
// Sample test values (you can modif y these to test more cases)
int x = 6, y = 5;
int a = 3, b = 4, g = 5;
int i = 4, j = 7;
cout << “a) original == rewritten? “ << (original_a == rewritten_a ? “true” : “false”) <<
endl;
// b) !( a == b ) || !( g != 5 )
bool original_b = !(a == b) || !(g != 5);
49
bool rewritten_b = (a != b) || (g == 5);
cout << “b) original == rewritten? “ << (original_b == rewritten_b ? “true” : “false”) <<
endl;
cout << “c) original == rewritten? “ << (original_c == rewritten_c ? “true” : “false”) <<
endl;
cout << “d) original == rewritten? “ << (original_d == rewritten_d ? “true” : “false”) <<
endl;
return 0;
}
5.23 (Diamond of Asterisks) Write a program that print s the following diamond shape. You may
use output statements that print a single asterisk (*), a single blank or a single newline.
Maximize your use of repetition (with nested for statements) and minimize the number of
output statements.
Answer
#include <iostream>
using namespace std;
50
int main() {
int n = 5; // number of lines in the top half (max stars = 2*n -1)
return 0;
}
5.24 (Diamond of Asterisks Modif ication) Modif y Exercise 5.23 to read an odd number in the
range 1 to 19 to specif y the number of rows in the diamond, then display a diamond of the
appropriate size.
Answer
#include <iostream>
using namespace std;
51
int main() {
int rows;
// Lower half
for (int i = n - 1; i >= 1; --i) {
for (int s = 1; s <= n - i; ++s) cout << “ “;
for (int star = 1; star <= 2 * i - 1; ++star) cout << “*”;
cout << endl;
}
return 0;
}
5.25 (Removing break and continue) A criticism of the break and continue statements is that
each is unstructured. These statements can always be replaced by structured statements.
Describe in general how you’d remove any break statement from a loop in a program and
52
replace it with some structured equivalent. [Hint : The break statement leaves a loop from
within the body of the loop. Another way to leave is by failing the loop-continuation test.
Consider using in the loop-continuation test a second test that indicates “early exit because of a
‘break’ condition.”] Use the technique you developed here to remove the break statement from
the program of Fig. 5.13.
Answer
#include <iostream>
using namespace std;
int main() {
int total = 0, grade;
int gradeCounter = 0;
bool done = false;
while (!done) {
cout << “Enter grade (-1 to end): “;
cin >> grade;
if (grade == -1)
done = true;
else {
total += grade;
gradeCounter++;
}
}
if (gradeCounter != 0)
cout << “Average: “ << static_cast<double >(total) / gradeCounter << endl;
else
cout << “No grades entered.\n”;
return 0;
}
5.26 (What Does This Code Do?) What does the following program segment do?
53
for ( unsigned int i = 1; i <= 5; ++i )
{
for ( unsigned int j = 1; j <= 3; ++j )
{
for ( unsigned int k = 1; k <= 4; ++k )
cout << '*';
Answer
5.27 (Removing the continue Statement) Describe in general how you’d remove any continue
statement from a loop in a program and replace it with some structured equivalent. Use the
technique you developed here to remove the continue statement from the program of Fig. 5.14.
Answer
#include <iostream>
using namespace std;
int main() {
for (int x = 1; x <= 10; ++x) {
if (x == 5)
continue; // skip the rest of the loop when x is 5
54
cout << “\nUsed continue to skip print ing 5\n”;
return 0;
}
5.28 (“The Twelve Days of Christmas” Song) Write a program that uses repetition and switch
statements to print the song “The Twelve Days of Christmas.” One switch statement should be
used to print the day (i.e., “first,” “second,” etc.). A separate switch statement should be used
to
print the remainder of each verse. Visit the website www.12days.com/library/carols/
12daysofxmas.htm for the complete lyrics to the song.
Answer
#include <iostream>
using namespace std;
int main() {
for (int day = 1; day <= 12; ++day) {
// First switch: print the day name
cout << “On the “;
switch (day) {
case 1: cout << “first”; break;
case 2: cout << “second”; break;
case 3: cout << “third”; break;
case 4: cout << “fourth”; break;
case 5: cout << “fif th”; break;
case 6: cout << “sixth”; break;
case 7: cout << “seventh”; break;
case 8: cout << “eighth”; break;
case 9: cout << “nint h”; break;
case 10: cout << “tenth”; break;
case 11: cout << “eleventh”; break;
case 12: cout << “twelfth”; break;
}
55
cout << “ day of Christmas, my true love sent to me:\n”;
return 0;
}
5.29 (Peter Minuit Problem) Legend has it that, in 1626, Peter Minuit purchased Manhattan
Island for $24.00 in barter. Did he make a good investment? To answer this question, modif y
the
compound int erest program of Fig. 5.6 to begin with a principal of $24.00 and to calculate the
amount of int erest on deposit if that money had been kept on deposit until this year (e.g., 387
years through 2013). Place the for loop that performs the compound int erest calculation in an
outer for loop that varies the int erest rate from 5% to 10% to observe the wonders of
compound int erest.
56
Answer
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
const double principal = 24.00;
const int years = 387;
cout << “Yearly compound int erest for Peter Minuit’s $24 investment over 387
years:\n\n”;
cout << “At “ << (rate * 100) << “% int erest: $” << amount << endl;
}
return 0;
}
57