0% found this document useful (0 votes)
4 views58 pages

Programming Group Assibnment

The document outlines a series of programming assignments focused on C++ exercises, including correcting code errors, calculating gas mileage, determining credit limits, and calculating salaries. Each exercise includes example code, expected outputs, and explanations of the program's functionality. The assignments aim to reinforce programming concepts and improve coding skills through practical applications.

Uploaded by

Habtsh tube
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views58 pages

Programming Group Assibnment

The document outlines a series of programming assignments focused on C++ exercises, including correcting code errors, calculating gas mileage, determining credit limits, and calculating salaries. Each exercise includes example code, expected outputs, and explanations of the program's functionality. The assignments aim to reinforce programming concepts and improve coding skills through practical applications.

Uploaded by

Habtsh tube
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Write a C++

Program
Intro. Computer sceience
and programing 1

1. Habtemariam Delelew UUR00010/17


2. Benion Mulugeta UUR00164/17
3. Biniyam Yosef UUR00088/17
Programming Assignments
Exercises

4.11 (Correct the Code Errors) Identif y and correct the error(s) in each of the following:

a) if (age >= 65 );

cout << “Age is greater than or equal to 65” << endl;

else

cout << “Age is less than 65 << endl”;

Corrected

if (age >= 65)

cout << “Age is greater than or equal to 65” << endl;

else

cout << “Age is less than 65” << endl;

b) if ( age >= 65 )

cout << “Age is greater than or equal to 65” << endl;

else;

cout << “Age is less than 65 << endl”;

Corrected

if (age >= 65)

cout << “Age is greater than or equal to 65” << endl;

else

cout << “Age is less than 65” << endl;

c) unsigned int x = 1;

unsigned int total;

while ( x <= 10 ){

total += x;

1
++x;

Corrected

unsigned int x = 1;

unsigned int total = 0;

while ( x <= 10 ){

total += x;

++x;

d) While ( x <= 100 )

total += x;

++x;

Corrected

while (x <= 100) {

total += x;

++x;}

e) while ( y > 0 ){

cout << y << endl;

++y;

Corrected

while (y > 0){

cout << y << endl;

--y;

2
4.12 (What Does this Program Do?) What does the following program print ?

// Exercise 4.12: ex04_12.cpp

// What does this program print ?

#include <iostream>

using namespace std;

int main() {

unsigned int y = 0; // declare and initialize y

unsigned int x = 1; // declare and initialize x

unsigned int total = 0; // declare and initialize total

while ( x <= 10 ) // loop 10 times

y = x * x; // perform calculation

cout << y << endl; // output result

total += y; // add y to total

++x; // increment counter x

} // end while

cout << “Total is “ << total << endl; // display result

} // end main

Answer: This C++ program:

1. Loops from x = 1 to x = 10

2. In each loop:

o Calculates y = x * x (i.e., the square of x)

o Print s that square

o Adds it to a running total

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 .

Enter miles driven (-1 to quit): 287

Enter gallons used: 13

MPG this trip: 22.076923

Total MPG: 22.076923

Enter miles driven (-1 to quit): 200

Enter gallons used: 10

MPG this trip: 20.000000

Total MPG: 21.173913

Enter the miles driven (-1 to quit): 120

Enter gallons used: 5

4
MPG this trip: 24.000000

Total MPG: 21.678571

Enter the miles used (-1 to quit): -1

Answer : C++ Program

#include <iostream>

using namespace std;

int main() {

double miles, gallons;

double totalMiles = 0;

double totalGallons = 0;

cout << “Enter miles driven (-1 to quit): “;

cin >> miles;

while (miles != -1) {

cout << “Enter gallons used: “;

cin >> gallons;

double mpg = miles / gallons;

cout << “MPG this trip: “ << mpg << endl;

totalMiles += miles;

totalGallons += gallons;

double totalMPG = totalMiles / totalGallons;

cout << “Total MPG: “ << totalMPG << endl;

cout << “Enter miles driven (-1 to quit): “;

cin >> miles;

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 .

Enter miles driven (-1 to quit): 287

Enter gallons used: 13

MPG this trip: 22.076923

Total MPG: 22.076923

Enter miles driven (-1 to quit): 200

Enter gallons used: 10

MPG this trip: 20.000000

Total MPG: 21.173913

Enter the miles driven (-1 to quit): 120

Enter gallons used: 5

MPG this trip: 24.000000

Total MPG: 21.678571

Enter the miles used (-1 to quit): -1

Answer : C++ Program

#include <iostream>

using namespace std;

int main() {

double miles = 0.0, gallons = 0.0;

double totalMiles = 0.0, totalGallons = 0.0;

cout << “Enter miles driven (-1 to quit): “;

cin >> miles;

6
while (miles != -1) {

cout << “Enter gallons used: “;

cin >> gallons;

double mpgTrip = miles / gallons;

cout << “MPG this trip: “ << mpgTrip << endl;

totalMiles += miles;

totalGallons += gallons;

double totalMPG = totalMiles / totalGallons;

cout << “Total MPG: “ << totalMPG << endl;

cout << “Enter miles driven (-1 to quit): “;

cin >> miles;

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:

a) Account number (an int eger)

b) Balance at the beginning of the month

c) Total of all items charged by this customer this month

d) Total of all credits applied to this customer's account this month

e) Allowed credit limit

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.”

Enter account number (or -1 to quit): 100

Enter beginning balance: 5394.78

Enter total charges: 1000.00

Enter total credits: 500.00

Enter credit limit: 5500.00

New balance is 5894.78

Account: 100

Credit limit: 5500.00

Balance: 5894.78

Credit Limit Exceeded.

Enter Account Number (or -1 to quit): 200

Enter beginning balance: 1000.00

Enter total charges: 123.45

Enter total credits: 321.00

Enter credit limit: 1500.00

New balance is 802.45

Enter Account Number (or -1 to quit): -1

Answer : C++ Program

#include <iostream>

#include <iomanip> // For formatting output

using namespace std;

int main() {

int accountNumber;

8
double beginningBalance, totalCharges, totalCredits, creditLimit, newBalance;

cout << fixed << setprecision(2); // Format output to 2 decimal places

cout << “Enter account number (or -1 to quit): “;

cin >> accountNumber;

while (accountNumber != -1) {

cout << “Enter beginning balance: “;

cin >> beginningBalance;

cout << “Enter total charges: “;

cin >> totalCharges;

cout << “Enter total credits: “;

cin >> totalCredits;

cout << “Enter credit limit: “;

cin >> creditLimit;

newBalance = beginningBalance + totalCharges - totalCredits;

cout << “New balance is “ << newBalance << endl;

if (newBalance > creditLimit) {

cout << “Account: “ << accountNumber << endl;

cout << “Credit limit: “ << creditLimit << endl;

cout << “Balance: “ << newBalance << endl;

cout << “Credit Limit Exceeded.” << endl;

cout << “Enter account number (or -1 to quit): “;

cin >> accountNumber;

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.

Enter sales in dollars (-1 to end): 5000.00

Salary is: $650.00

Enter sales in dollars (-1 to end): 6000.00

Salary is: $740.00

Enter sales in dollars (-1 to end): 7000.00

Salary is: $830.00

Enter sales in dollars (-1 to end): -1

Answer : C++ Program

#include <iostream>

#include <iomanip>

using namespace std;

int main() {

double grossSales;

const double baseSalary = 200.0;

const double commissionRate = 0.09;

cout << fixed << setprecision(2);

cout << “Enter sales in dollars (-1 to end): “;

cin >> grossSales;

10
while (grossSales != -1) {

double salary = baseSalary + commissionRate * grossSales;

cout << “Salary is: $” << salary << endl;

cout << “Enter sales in dollars (-1 to end): “;

cin >> grossSales;

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.

Enter hours worked (-1 to end): 39

Enter hourly rate of the employee ($00.00): 10.00

Salary is $390.00

Enter hours worked (-1 to end): 40

Enter hourly rate of the employee ($00.00): 10.00

Salary is $400.00

Enter hours worked (-1 to end): 41

Enter hourly rate of the employee ($00.00): 10.00

Salary is $415.00

Enter hours worked (-1 to end): -1

11
Answer : C++ Program

#include <iostream>

#include <iomanip>

using namespace std;

int main() {

double hoursWorked, hourlyRate, grossPay;

cout << fixed << setprecision(2);

cout << “Enter hours worked (-1 to end): “;

cin >> hoursWorked;

while (hoursWorked != -1) {

cout << “Enter hourly rate of the employee ($00.00): “;

cin >> hourlyRate;

if (hoursWorked <= 40) {

grossPay = hoursWorked * hourlyRate;

} else {

grossPay = 40 * hourlyRate + (hoursWorked - 40) * hourlyRate * 1.5;

cout << “Salary is $” << grossPay << endl;

cout << “Enter hours worked (-1 to end): “;

cin >> hoursWorked;

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).

number: The current number input to the program.

largest: The largest number found so far.

Answer : C++ Program

#include <iostream>

using namespace std;

int main() {

int counter = 1;

int number;

int largest;

cout << “Enter number 1: “;

cin >> number;

largest = number;

while (counter < 10) {

counter++;

cout << “Enter number “ << counter << “: “;

cin >> number;

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:

N 10*N 100*N 1000*N

1 10 100 1000

2 20 200 2000

3 30 300 3000

4 40 400 4000

5 50 500 5000

Answer : C++ Program

#include <iostream>

using namespace std;

int main() {

int N = 1;

cout << “N\t10*N\t100*N\t1000*N\n”;

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.]

Answer : C++ Program

#include <iostream>

using namespace std;

int main() {

int counter = 1;

int number;

int largest, secondLargest;

cout << “Enter number 1: “;

cin >> number;

largest = number;

secondLargest = number;

while (counter < 10) {

counter++;

cout << “Enter number “ << counter << “: “;

cin >> number;

if (number > largest) {

secondLargest = largest;

largest = number;

else if (number > secondLargest) {


15
secondLargest = 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.

Answer : C++ Program

#include <iostream>

using namespace std;

int main() {

int answer;

cout << “Enter your answer (1 or 2): “;

cin >> answer;

while (answer != 1 && answer != 2) {

cout << “Invalid input. Please enter 1 or 2: “;

cin >> answer;

cout << “You entered: “ << answer << endl;

return 0;

16
4.21 (What Does this Program Do?) What does the following program print ?

// Exercise 4.21: ex04_21.cpp

// What does this program print ?

#include <iostream>

using namespace std;

int main(){

unsigned int count = 1; // initialize count

while ( count <= 10 ) // loop 10 times

// output line of text

cout << ( count % 2 ? “****” : “++++++++” ) << endl;

++count; // increment count

} // end while

} // end main

Answer : C++ Output

****

++++++++

****

++++++++

****

++++++++

****

++++++++

****

++++++++

17
4.22 (What Does this Program Do?) What does the following program print ?

// Exercise 4.22: ex04_22.cpp

// What does this program print ?

#include <iostream>

using namespace std;

int main() {

unsigned int row = 10; // initialize row

while ( row >= 1 ) // loop until row < 1

unsigned int column = 1; // set column to 1 as iteration begins

while ( column <= 10 ) // loop 10 times

cout << ( row % 2 ? “<“ : “>“ ); // output

++column; // increment column

} // end inner while

--row; // decrement row

cout << endl; // begin new output line

} // end outer while

} // end main

Answer : C++ Output

>>>>>>>>>>

<<<<<<<<<<

>>>>>>>>>>

<<<<<<<<<<

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 )

cout << “*****” << endl;

else

cout << “#####” << endl;

cout << “$$$$$” << endl;

Answer : C++ Program

if ( x < 10 )

if ( y > 10 )

cout << “*****” << endl;

else

cout << “#####” << endl;

cout << “$$$$$” << endl;

b) if ( x < 10 ){

if ( y > 10 )

19
cout << “*****” << endl;

else

cout << “#####” << endl;

cout << “$$$$$” << endl;

Answer : C++ Program

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 )

cout << “@@@@@” << endl;

else

cout << “#####” << endl;

cout << “$$$$$” << endl;

cout << “&&&&&” << endl;

20
a) Assuming x = 5 and y = 8, the following output is produced.

@@@@@
$$$$$
&&&&&

Answer

if ( y == 8 ) {

if ( x == 5 )

cout << “@@@@@” << endl;

cout << “$$$$$” << endl;

cout << “&&&&&” << endl;

b) Assuming x = 5 and y = 8, the following output is produced.


@@@@@

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 )

cout << “@@@@@” << endl;

cout << “&&&&&” << endl;

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 )

cout << “@@@@@” << endl;

else {

cout << “#####” << endl;

cout << “$$$$$” << endl;

cout << “&&&&&” << endl;

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;

cout << “Enter the size of the square (1 to 20): “;


cin >> size;

if (size < 1 || size > 20) {


cout << “Invalid size. Please enter a number between 1 and 20.” << endl;
return 1; // exit the program
}
int row = 1;

while (row <= size) {


int col = 1;

while (col <= size) {


// Print '*' at the borders, space inside

if (row == 1 || row == size || col == 1 || col == size)


cout << “*”;
else
cout << “ “;
++col;
}

cout << endl; // move to next line


++row;
}

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;

double diameter = 2 * radius;


double circumference = 2 * pi * radius;
double area = pi * radius * radius;

cout << fixed << setprecision(4);


cout << “Diameter: “ << diameter << endl;
cout << “Circumference: “ << circumference << endl;
cout << “Area: “ << area << endl;
return 0;

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;

cout << “Enter three nonzero side lengths: “;


cin >> a >> b >> c;

// Check for nonzero values


if (a <= 0 || b <= 0 || c <= 0) {
cout << “All sides must be nonzero positive values.” << endl;
return 1;
}

// Check triangle inequality


if ((a + b > c) && (b + c > a) && (a + c > b)) {
cout << “These sides CAN form a triangle.” << endl;
} else {
cout << “These sides CANNOT form a triangle.” << endl;
}

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;

cout << “Enter three nonzero side lengths: “;


cin >> a >> b >> c;

// Check for nonzero and positive values


if (a <= 0 || b <= 0 || c <= 0) {
cout << “All sides must be positive nonzero int egers.” << endl;
return 1;
}
// Sort the sides so that c is the largest
int sides[3] = {a, b, c};
sort(sides, sides + 3); // sides[2] will be the largest

// Check the Pythagorean condition


if (sides[0]*sides[0] + sides[1]*sides[1] == sides[2]*sides[2]) {
cout << “These sides CAN form a right triangle.” << endl;
} else {
cout << “These sides CANNOT form a right triangle.” << endl;
}
return 0;
}

4.34 (Factorial) The factorial of a nonnegative int eger n is written n! (pronounced “n


factorial”) and is defined as follows:
n! = n · (n – 1) · (n – 2) · … · 1 (for values of n greater than 1)
and
n! = 1 (for n = 0 or n = 1).
For example, 5! = 5 · 4 · 3 · 2 · 1, which is 120. Use while statements in each of the following:

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

cout << “Enter a nonnegative int eger: “;


cin >> n;
unsigned int i = n;
while (i > 1) {
fact *= i;
--i;
}
cout << n << “! = “ << fact << endl;
return 0;
}

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;
}

c) Write a program that computes the value of ex 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() {
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

for (int x = 19; x >= 1; x -= 2)


cout << x << endl;

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;

for (int i = 1; i <= count; ++i) {


cout << “Enter value “ << i << “: “;
cin >> number;
sum += number;
}
cout << “The total sum is: “ << sum << endl;
return 0;
}

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;

cout << “Enter int egers (9999 to stop): “;

for (;;) { // infinite loop


cin >> number;

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?

// Exercise 5.7: ex05_07.cpp


// What does this program do?
#include <iostream>
using namespace std;

int main()
{
unsigned int x; // declare x
unsigned int y; // declare y

// prompt user for input


cout << “Enter two int egers in the range 1-20: “;
cin >> x >> y; // read values for x and y

for ( unsigned int i = 1; i <= y; ++i ) // count from 1 to y


{
for ( unsigned int j = 1; j <= x; ++j ) // count from 1 to x
cout << '@'; // output @

cout << endl; // begin new line


} // end outer for
// end main

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() {

int count, number, smallest;

cout << “How many numbers will you enter? “;


cin >> count;

cout << “Enter number 1: “;


cin >> number;
smallest = number; // Initialize smallest with the first number

for (int i = 2; i <= count; ++i) {


cout << “Enter number “ << i << “: “;
cin >> number;

if (number < smallest)


smallest = number;
}

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

for (int i = 1; i <= 15; i += 2) { // Increment by 2 to get only odd numbers


product *= i;
}

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;

for (int i = 1; i <= n; ++i) {


factorial *= i;
}

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

using namespace std;

int main() {
double principal;
int years;

cout << “Enter the principal amount: “;


cin >> principal;

cout << “Enter the number of years: “;


cin >> years;

cout << fixed << setprecision(2);


cout << “Int erest Rate (%) Amount on Deposit” << endl;
cout << “-------------------------------------” << endl;

for (int rate = 5; rate <= 10; ++rate) {


double amount = principal * pow(1 + rate / 100.0, years);
cout << setw(17) << rate << setw(20) << amount << endl;
}
return 0;
}
5.12 (Drawing Patterns with Nested for Loops) Write a program that uses for statements to

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;

for (int i = rows; i >= 1; i--) {


for (int j = 1; j <= i; j++) {
cout << “*”;

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>

using namespace std;

int main() {
int rows = 10;

for (int i = 1; i <= rows; i++) {


// Print leading spaces
for (int j = 1; j <= rows - i; j++) {
cout << “ “;
}
for (int k = 1; k <= i; k++) {
cout << “*”;
}

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];
}

// Print bar chart


for (int i = 0; i < count; ++i) {
for (int j = 0; j < numbers[i]; ++j) {
cout << '*';
}
cout << endl;
}

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;

cout << “Enter product number and quantity sold (0 to end):\n”;

while (true) {
cout << “Product number (1-5, 0 to quit): “;
cin >> productNumber;
if (productNumber == 0)
break;

cout << “Quantity sold: “;


cin >> quantity;

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
}

totalSales += price * quantity;


}

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;

cout << “Enter letter grades (A-F). Enter 'Q' to quit:\n”;

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;

cout << “Enter principal amount (dollars only): “;


cin >> principalDollars;

cout << “Enter annual int erest rate (percent): “;


cin >> int erestRatePercent;

cout << “Enter number of years: “;


cin >> years;

// Convert principal to cents


long long principalCents = static_cast<long long>(principalDollars) * 100;
long long amountCents = principalCents;

for (int i = 0; i < years; ++i) {


amountCents = (amountCents * (100 + int erestRatePercent)) / 100;
}
// Split amountCents int o dollars and cents

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

using namespace std;

// Function to return binary representation of an int eger as a string


string toBinary(int n) {
// Use 8 bits for binary representation
return bitset<8>(n).to_string();
}

int main() {
cout << left << setw(10) << “Decimal”
<< setw(12) << “Binary”
<< setw(10) << “Octal”
<< setw(12) << “Hexadecimal” << endl;

cout << “----------------------------------------” << endl;

for (int i = 1; i <= 256; ++i) {


cout << dec << setw(10) << i;
cout << setw(12) << toBinary(i);
cout << oct << setw(10) << i;
cout << hex << uppercase << setw(12) << i << endl;

44
}

return 0;
}

5.19 (Calculating π) Calculate the value of π from the infinite series

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;

for (int term = 1; term <= 1000; ++term) {


double denominator = 2 * term - 1;
pi_over_4 += sign * (1.0 / denominator);
sign = -sign; // flip sign for next term

double pi_approx = 4 * pi_over_4;

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”;

for (int hyp = 1; hyp <= max_side; ++hyp) {


for (int side1 = 1; side1 <= hyp; ++side1) {
for (int side2 = side1; side2 <= hyp; ++side2) { // start from side1 to avoid duplicates
if (side1 * side1 + side2 * side2 == hyp * hyp) {
cout << “(“ << side1 << “, “ << side2 << “, “ << hyp << “)\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';

while (continueInput == 'y' || continueInput == 'Y') {


cout << “Enter employee pay code (1=Manager, 2=Hourly, 3=Commission,
4=Pieceworker): “;
cin >> payCode;

double weeklyPay = 0.0;

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;

if (hoursWorked <= 40) {


weeklyPay = hourlyWage * hoursWorked;
} else {
double overtimeHours = hoursWorked - 40;
weeklyPay = (hourlyWage * 40) + (overtimeHours * hourlyWage * 1.5);
}
break;
}
case 3: {
// Commission worker: $250 + 5.7% of sales
double grossSales;
cout << “Enter gross weekly sales: $”;
cin >> grossSales;
weeklyPay = 250 + (0.057 * grossSales);
break;
}
case 4: {
// Pieceworker: fixed amount per item * number of items produced
double wagePerItem;
int itemsProduced;
cout << “Enter wage per item: $”;
cin >> wagePerItem;
cout << “Enter number of items produced: “;
cin >> itemsProduced;
weeklyPay = wagePerItem * itemsProduced;
break;
}
default:
cout << “Invalid pay code entered.\n”;
continue; // skip rest of loop and ask again
}

cout << “Weekly pay is: $” << weeklyPay << “\n”;

cout << “Do you want to process another employee? (y/n): “;


cin >> continueInput;

48
}

cout << “Payroll processing completed.\n”;


return 0;
}

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;

// a) !( x < 5 ) && !( y >= 7 )


bool original_a = !(x < 5) && !(y >= 7);
bool rewritten_a = (x >= 5) && (y < 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;

// c) !(( x <= 8 ) && ( y > 4 ))


bool original_c = !((x <= 8) && (y > 4));
bool rewritten_c = (x > 8) || (y <= 4);

cout << “c) original == rewritten? “ << (original_c == rewritten_c ? “true” : “false”) <<
endl;

// d) !(( i > 4 ) || ( j <= 6 ))


bool original_d = !((i > 4) || (j <= 6));
bool rewritten_d = (i <= 4) && (j > 6);

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)

// Upper part of the diamond (include middle line)


for (int i = 1; i <= n; ++i) {
// print spaces
for (int j = 1; j <= n - i; ++j) {
cout << “ “;
}
// print stars
for (int j = 1; j <= 2 * i - 1; ++j) {
cout << “*”;
}
cout << endl;
}

// Lower part of the diamond


for (int i = n - 1; i >= 1; --i) {
// print spaces
for (int j = 1; j <= n - i; ++j) {
cout << “ “;
}
// print stars
for (int j = 1; j <= 2 * i - 1; ++j) {
cout << “*”;
}
cout << endl;
}

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;

// Input: must be an odd number between 1 and 19


do {
cout << “Enter an odd number between 1 and 19: “;
cin >> rows;

if (rows < 1 || rows > 19 || rows % 2 == 0) {


cout << “Invalid input. Try again.\n”;
}

} while (rows < 1 || rows > 19 || rows % 2 == 0);

int n = rows / 2 + 1; // Half of the diamond (include the middle)

// Upper half include the middle line


for (int i = 1; i <= n; ++i) {
for (int s = 1; s <= n - i; ++s) cout << “ “;
for (int star = 1; star <= 2 * i - 1; ++star) cout << “*”;
cout << endl;
}

// 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 << '*';

cout << endl;


} // end inner for
cout << endl;
} // end outer for

Answer

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 << '*';

cout << endl;


}
cout << endl;
}

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

cout << x << “ “;


}

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”;

// Second switch: print the gif ts (with fall-through)


switch (day) {
case 12: cout << “Twelve drummers drumming,\n”;
case 11: cout << “Eleven pipers piping,\n”;
case 10: cout << “Ten lords a-leaping,\n”;
case 9: cout << “Nine ladies dancing,\n”;
case 8: cout << “Eight maids a-milking,\n”;
case 7: cout << “Seven swans a-swimming,\n”;
case 6: cout << “Six geese a-laying,\n”;
case 5: cout << “Five golden rings,\n”;
case 4: cout << “Four calling birds,\n”;
case 3: cout << “Three French hens,\n”;
case 2: cout << “Two turtle doves,\n”;
case 1:
if (day == 1)
cout << “A partridge in a pear tree.\n”;
else
cout << “And a partridge in a pear tree.\n”;
break;
}

cout << endl;


}

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 << fixed << setprecision(2);

cout << “Yearly compound int erest for Peter Minuit’s $24 investment over 387
years:\n\n”;

// Int erest rates from 5% to 10%


for (double rate = 0.05; rate <= 0.10; rate += 0.01) {
double amount = principal * pow(1 + rate, years);

cout << “At “ << (rate * 100) << “% int erest: $” << amount << endl;
}

return 0;
}

57

You might also like