Você está na página 1de 52

4

Lets all move one place on.

Control
Statements:
Part 1

Lewis Carroll

The wheel is come full circle.


William Shakespeare

How many apples fell on


Newtons head before he took
the hint!
Robert Frost

All the evolution we know of


proceeds from the vague to
the denite.
Charles Sanders Peirce

OBJECTIVES
In this chapter you will learn:

Basic problem-solving techniques.


To develop algorithms through the process of top-down,
stepwise renement.
To use the if and ifelse selection statements to
choose among alternative actions.
To use the while repetition statement to execute
statements in a program repeatedly.
Counter-controlled repetition and sentinel-controlled
repetition.
To use the increment, decrement and assignment
operators.

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 4 Control Statements: Part 1

Self-Review Exercises
4.1

Answer each of the following questions.


a) All programs can be written in terms of three types of control structures:
,
and
.
ANS: Sequence, selection and repetition.
b) The
selection statement is used to execute one action when a condition is
true or a different action when that condition is false.
ANS: ifelse.
repetition.
c) Repeating a set of instructions a specific number of times is called
ANS: Counter-controlled or definite.
d) When it is not known in advance how many times a set of statements will be repeated,
a(n)
value can be used to terminate the repetition.
ANS: Sentinel, signal, flag or dummy.

4.2

Write four different C++ statements that each add 1 to integer variable x.
ANS: x = x + 1;

+= 1;

++x;
x++;

4.3

Write C++ statements to accomplish each of the following:


a) In one statement, assign the sum of the current value of x and y to z and postincrement
the value of x.
ANS: z = x++ + y;

b) Determine whether the value of the variable

count

is greater than 10. If it is, print

"Count is greater than 10."

ANS: if ( count > 10 )


cout << "Count is greater than 10" << endl;

c) Predecrement the variable x by 1, then subtract it from the variable total.


ANS: total -= --x;

d) Calculate the remainder after q is divided by divisor and assign the result to q. Write
this statement two different ways.
ANS: q %= divisor;
q = q % divisor;

4.4

Write C++ statements to accomplish each of the following tasks.


a) Declare variables sum and x to be of type int.
ANS: int sum;
int x;

b) Set variable x to 1.
ANS: x = 1;

c) Set variable sum to 0.


ANS: sum = 0;

d) Add variable x to variable sum and assign the result to variable sum.
ANS: sum += x;

or

sum = sum + x;

e) Print "The

sum is: "

followed by the value of variable sum.

ANS: cout << "The sum is: " << sum << endl;

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Self-Review Exercises

4.5
Combine the statements that you wrote in Exercise 4.4 into a program that calculates and
prints the sum of the integers from 1 to 10. Use the while statement to loop through the calculation
and increment statements. The loop should terminate when the value of x becomes 11.
ANS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

// Exercise 4.5 Solution: ex04_05.cpp


// Calculate the sum of the integers from 1 to 10.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int sum; // stores sum of integers 1 to 10
int x; // counter
x = 1; // count from 1
sum = 0; // initialize sum
while ( x <= 10 ) // loop 10 times
{
sum += x; // add x to sum
x++; // increment x
} // end while
cout << "The sum is: " << sum << endl;
return 0; // indicate successful termination
} // end main

The sum is: 55

4.6
State the values of each variable after the calculation is performed. Assume that, when each
statement begins executing, all variables have the integer value 5.
a) product *= x++;
ANS: product = 25, x = 6;

b)

quotient /= ++x;

ANS: quotient = 0, x = 6;

1
2
3
4
5
6
7
8
9
10
11
12
13
14

// Exercise 4.6 Solution: ex04_06.cpp


// Calculate the value of product and quotient.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int x = 5;
int product = 5;
int quotient = 5;
// part a
product *= x++; // part a statement

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

4
15
16
17
18
19
20
21
22
23
24

Chapter 4 Control Statements: Part 1

cout << "Value of product after calculation: " << product << endl;
cout << "Value of x after calculation: " << x << endl << endl;
// part b
x = 5; // reset value of x
quotient /= ++x; // part b statement
cout << "Value of quotient after calculation: " << quotient << endl;
cout << "Value of x after calculation: " << x << endl << endl;
return 0; // indicate successful termination
} // end main

Value of product after calculation: 25


Value of x after calculation: 6
Value of quotient after calculation: 0
Value of x after calculation: 6

4.7

Write single C++ statements that do the following:


a) Input integer variable x with cin and >>.
ANS: cin >> x;

b) Input integer variable y with cin and >>.


ANS: cin >> y;

c) Set integer variable i to 1.


ANS: i = 1;

d) Set integer variable power to 1.


ANS: power = 1;

e) Multiply variable power by x and assign the result to power.


ANS: power *= x;

or

power = power * x;

f) Postincrement variable i by 1.
ANS: i++;

g) Determine whether i is less than or equal to y.


ANS: if ( i <= y )

h) Output integer variable power with cout and <<.


ANS: cout << power << endl;

4.8
Write a C++ program that uses the statements in Exercise 4.7 to calculate x raised to the y
power. The program should have a while repetition statement.
ANS:

1
2
3
4
5
6
7
8
9

// Exercise 4.8 Solution: ex04_08.cpp


// Raise x to the y power.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Self-Review Exercises
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

int
int
int
int

x; // base
y; // exponent
i; // counts from 1 to y
power; // used to calculate x raised to power y

i = 1; // initialize i to begin counting from 1


power = 1; // initialize power
cout << "Enter base as an integer: ";
cin >> x; // input base

// prompt for base

cout << "Enter exponent as an integer: "; // prompt for exponent


cin >> y; // input exponent
// count from 1 to y and multiply power by x each time
while ( i <= y )
{
power *= x;
i++;
} // end while
cout << power << endl; // display result
return 0; // indicate successful termination
} // end main

Enter base as an integer: 2


Enter exponent as an integer: 3
8

4.9

Identify and correct the errors in each of the following:


a) while ( c <= 5 )
{
product *= c;
c++;

ANS: Error: Missing the closing right brace of the while body.

Correction: Add closing right brace after the statement c++;.

b)

cin << value;

c)

if ( gender == 1 )

ANS: Error: Used stream insertion instead of stream extraction.

Correction: Change << to >>.


cout << "Woman" << endl;

else;
cout << "Man" << endl;

ANS: Error: Semicolon after else results in a logic error. The second output statement will

always be executed.
Correction: Remove the semicolon after else.

4.10

What is wrong with the following while repetition statement?

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 4 Control Statements: Part 1


while ( z >= 0 )
sum += z;

ANS: The value of the variable z is never changed in the while statement. Therefore, if the

loop-continuation condition (z >= 0) is initially true, an infinite loop is created. To


prevent the infinite loop, z must be decremented so that it eventually becomes less
than 0.

Exercises
4.11

Identify 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";

ANS: The semicolon at the end of the if condition should be removed. The closing double

b)

quote after the second endl should be placed after 65.

if ( age >= 65 )
cout << "Age is greater than or equal to 65" << endl;
else;
cout << "Age is less than 65 << endl";

ANS: The semicolon after the else should be removed. The closing double quote after the

c)

second endl should be placed after 65.

int x = 1, total;
while ( x <= 10 )
{
total += x;
x++;
}

ANS: Variable total should be initialized to 0.

d)

While ( x <= 100 )


total += x;
x++;

ANS: The W in while should be lowercase. The whiles body should be enclosed in braces

e)

{}.

while ( y > 0 )
{
cout << y << endl;
y++;
}

ANS: The variable y should be decremented (i.e., y--;) not incremented ( y++;).

4.12

What does the following program print?

ANS: The program prints the squares of the integers from 1 to 10 and the sum of those

squares.

1
2
3
4

// Exercise 4.12 Solution: ex04_12.cpp


// What does this program print?
#include <iostream>
using std::cout;

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

using std::endl;
int main()
{
int y; // declare y
int x = 1; // initialize x
int total = 0; // 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
return 0; // indicate successful termination
} // end main

1
4
9
16
25
36
49
64
81
100
Total is 385

For Exercise 4.13 to Exercise 4.16, perform each of these steps:


a)
b)
c)
d)

Read the problem statement.


Formulate the algorithm using pseudocode and top-down, stepwise refinement.
Write a C++ program.
Test, debug and execute the C++ program.

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Chapter 4 Control Statements: Part 1

4.13 Drivers are concerned with the mileage obtained by their automobiles. One driver has kept
track of several tankfuls of gasoline by recording miles driven and gallons used for each tankful. Develop a C++ program that uses a while statement to input the miles driven and gallons used for each
tankful. The program should calculate and display the miles per gallon obtained for each tankful
and print the combined miles per gallon obtained for all tankfuls up to this point.
Enter the miles used (-1 to quit): 287
Enter gallons: 13
MPG this tankful: 22.076923
Total MPG: 22.076923
Enter the miles used (-1 to quit): 200
Enter gallons: 10
MPG this tankful: 20.000000
Total MPG: 21.173913
Enter the miles used (-1 to quit): 120
Enter gallons: 5
MPG this tankful: 24.000000
Total MPG: 21.678571
Enter the miles used (-1 to quit): -1

ANS:

Top:

Determine the current and combined miles/gallon for each tank of gas
First refinement:
Initialize variables
Input the miles driven and the gallons used
Calculate and print the miles/gallon for each tank of gas
Calculate and print the overall average miles/gallon
Second refinement:
Initialize totalGallons to zero
Initialize totalMiles to zero
Prompt the user to enter the miles used for the rst tank
Input the miles used for the rst tank (possibly the sentinel)
While the sentinel value (-1) has not been entered for the miles
Prompt the user to enter the gallons used for the current tank
Input the gallons used for the current tank
Add miles to the running total in totalMiles
Add gallons to the running total in totalGallons
If gallons is not zero
Calculate and print the miles/gallon
If totalGallons is not zero
Calculate and print the totalMiles/totalGallons
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
Prompt the user for the next tanks number of miles
Input the gallons used for the next tank

1
2
3
4
5
6
7
8
9
10

// Exercise 4.13 Solution: Gas.h


// Definition of class Gas that calculates average mpg.
// Member functions are defined in Gas.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

// Exercise 4.13 Solution: Gas.cpp


// Member-function definitions for class Gas that calculates
// average mpg with sentinel-controlled repetition.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::fixed;

// Gas class definition


class Gas
{
public:
void calculateMPG(); // function to calculate average mpg
}; // end class Gas

#include "Gas.h" // include definition of class Gas from Gas.h


// function to calculate average mpg
void Gas::calculateMPG()
{
double gallons; // gallons used for current tank
double miles; // miles driven for current tank
double totalGallons = 0; // total gallons used
double totalMiles = 0; // total miles driven
double milesPerGallon; // miles per gallon for tankful
double totalMilesPerGallon; // miles per gallon for trip
// processing phase
// get miles used for first tank
cout << "Enter the miles used (-1 to quit): ";
cin >> miles;
cout << fixed; // set floating-point number format
// exit if the input is -1 otherwise, proceed with the program
while ( miles != -1 )
{
// prompt user for gallons and obtain the input from user
cout << "Enter gallons: ";
cin >> gallons;
// add gallons and miles for this tank to total
totalMiles += miles;

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

10
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
1
2
3
4
5
6
7
8
9
10

Chapter 4 Control Statements: Part 1

totalGallons += gallons;
// calculate miles per gallon for the current tank
if ( gallons != 0 )
{
milesPerGallon = miles / gallons;
cout << "MPG this tankful: " << milesPerGallon;
} // end if
// calculate miles per gallon for the total trip
if ( totalGallons != 0 )
{
totalMilesPerGallon = totalMiles / totalGallons;
cout << "\nTotal MPG: " << totalMilesPerGallon;
} // end if
// prompt user for new value for miles
cout << "\n\nEnter the miles used (-1 to quit): ";
cin >> miles;
} // end while
} // end function calculateMPG

// Exercise 4.13 Solution: ex04_13.cpp


// Create Gas object and invoke its calculateMPG function.
#include "Gas.h" // include definition of class Gas from Gas.h
int main()
{
Gas myGas; // create Gas object myGas
myGas.calculateMPG(); // call its calculateMPG function
return 0; // indicate program ended successfully
} // end main

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


Enter gallons: 13
MPG this tankful: 22.076923
Total MPG: 22.076923
Enter the miles used (-1 to quit): 200
Enter gallons: 10
MPG this tankful: 20.000000
Total MPG: 21.173913
Enter the miles used (-1 to quit): 120
Enter gallons: 5
MPG this tankful: 24.000000
Total MPG: 21.678571
Enter the miles used (-1 to quit): -1

4.14 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 facts are available:

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises

11

a) Account number (an integer)


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 customers credit limit. For those customers whose credit limit is exceeded, the program should display
the customer's account number, credit limit, new balance and the message Credit Limit Exceeded.
Enter account number (-1 to end): 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): 300
Enter beginning balance: 500.00
Enter total charges: 274.73
Enter total credits: 100.00
Enter credit limit: 800.00
New balance is 674.73
Enter Account Number (or -1 to quit): -1

ANS:

Top:

Determine if each of an arbitrary number of department store customers has exceeded


the credit limit on a charge account
First refinement:
Input customers data
Calculate and display the customers new balance
Display message if users balance exceeds credit limit
Process next customer
Second refinement:
Prompt the user for the rst customers account number
Input the rst customers account number

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

12

Chapter 4 Control Statements: Part 1


While the sentinel value (-1) has not been entered for the account number
Prompt the user for the customers beginning balance
Input the customers beginning balance
Prompt the user for the customers total charges
Input the customers total charges
Prompt the user for the customers total credits
Input the customers total credits
Prompt the user for the customers credit limit
Input the customers credit limit
Calculate and display the customers new balance
If the balance exceeds the credit limit
Print the account number
Print the credit limit
Print the balance
Print Credit Limit Exceeded
Input the next customers account number

1
2
3
4
5
6
7
8
9
10
11

//
//
//
//

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

// Exercise 4.14 Solution: Credit.cpp


// Member-function definitions for class Credit that calculates
// credit balance.
#include <iostream>
using std::cin;
using std::cout;
using std::fixed;

Exercise 4.14 Solution: Credit.h


Definition of class Credit that calculates the balance on
several credit accounts.
Member functions are defined in Credit.cpp

// Credit class definition


class Credit
{
public:
void calculateBalance(); // function to calculate balance
}; // end class Credit

#include <iomanip> // parameterized stream manipulators


using std::setprecision; // sets numeric output precision
#include "Credit.h" // include definition of class Credit
// function to calculate balance
void Credit::calculateBalance()
{
int account; // account number
double balance; // account balance

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
1
2
3
4
5
6
7
8
9
10

double charges; // total charges


double credits; // total credits
double creditLimit; // allowed credit limit
cout << "Enter account number (-1 to end): ";
cin >> account; // read in account number
// set floating-point number format
cout << fixed << setprecision( 2 );
// exit if the input is -1 otherwise, proceed with the program
while ( account != -1 )
{
cout << "Enter beginning balance: ";
cin >> balance; // read in original balance
cout << "Enter total charges: ";
cin >> charges; // read in charges
cout << "Enter total credits: ";
cin >> credits; // read in credits
cout << "Enter credit limit: ";
cin >> creditLimit; // read in credit limit
// calculate and display new balance
balance = balance + charges - credits;
cout << "New balance is " << balance;
// display a warning if the user has exceed the credit limit
if ( balance > creditLimit )
cout << "\nAccount:
" << account
<< "\nCredit limit: " << creditLimit
<< "\nBalance:
" << balance
<< "\nCredit Limit Exceeded.";
cout << "\n\nEnter Account Number (or -1 to quit): ";
cin >> account; // read in next account number
} // end while
} // end function calculateBalance

// Exercise 4.14 Solution: ex04_14.cpp


// Create Credit object and invoke its calculateBalance function.
#include "Credit.h" // include definition of class Credit
int main()
{
Credit myCredit; // create Credit object myCredit
myCredit.calculateBalance(); // call its calculateBalance
return 0; // indicate program ended successfully
} // end main

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

13

14

Chapter 4 Control Statements: Part 1

Enter account number (-1 to end): 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): 300
Enter beginning balance: 500.00
Enter total charges: 274.73
Enter total credits: 100.00
Enter credit limit: 800.00
New balance is 674.73
Enter Account Number (or -1 to quit): -1

4.15 One large chemical company pays its salespeople on a commission basis. The salespeople each
receive $200 per week plus 9 percent of their gross sales for that week. For example, a salesperson who
sells $5000 worth of chemicals in a week receives $200 plus 9 percent of $5000, or a total of $650.
Develop a C++ program that uses a while statement to input each salespersons gross sales for last week
and calculates and displays that salespersons earnings. Process one salespersons 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

ANS:

Top:

For an arbitrary number of salespeople, determine each salespersons earnings for the
previous week
First refinement:
Input the rst salespersons sales for the week

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises

15

Calculate and print the salespersons wages for the week


Process the next salesperson
Second refinement:
Prompt the user for the rst salespersons sales in dollars
Input the rst salespersons sales in dollars
While the sentinel value (-1) has not been entered for the sales
Calculate the salespersons wages for the week as 200 dollars added to 9% of the
salespersons sales (calculated by multiplying the sales with .09)
Print the salespersons wages for the week
Prompt the user for the next salespersons sales in dollars
Input the next salespersons sales in dollars
1
2
3
4
5
6
7
8
9
10
11

//
//
//
//

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

// Exercise 4.15 Solution: Earnings.cpp


// Member-function definitions for class Earnings that calculates
// salesperson's earnings.
#include <iostream>
using std::cin;
using std::cout;
using std::fixed;

Exercise 4.15 Solution: Earnings.h


Definition of class Earnings that calculates
salesperson's earnings with sentinel-controlled repetition.
Member functions are defined in Earnings.cpp

// Earnings class definition


class Earnings
{
public:
void calculateEarnings(); // function to calculate earnings
}; // end class Earnings

#include <iomanip> // parameterized stream manipulators


using std::setprecision; // sets numeric output precision
#include "Earnings.h" // include definition of class Earnings
// function to calculate balance
void Earnings::calculateEarnings()
{
double sales; // gross weekly sales
double wage; // commissioned earnings
// processing phase
// get first sales
cout << "Enter sales in dollars (-1 to end): ";
cin >> sales;
// set floating-point number format

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

16
26
27
28
29
30
31
32
33
34
35
36
37
38
1
2
3
4
5
6
7
8
9
10

Chapter 4 Control Statements: Part 1

cout << fixed << setprecision( 2 );


// loop
while (
{
wage
cout

until sentinel value read from user


sales != -1.0 )
= 200.0 + 0.09 * sales; // calculate wage
<< "Salary is: $" << wage; // display salary

// prompt for next sales


cout << "\n\nEnter sales in dollars (-1 to end): ";
cin >> sales;
} // end while
} // end function calculateEarnings

// Exercise 4.15 Solution: ex04_15.cpp


// Create Earnings object and invoke its calculateEarnings function.
#include "Earnings.h" // include definition of class Earnings
int main()
{
Earnings myEarnings; // create Earnings object myEarnings
myEarnings.calculateEarnings(); // call its calculateEarnings
return 0; // indicate program ended successfully
} // end main

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

4.16
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

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises

17

rate of each employee. Your program should input this information for each employee and should
determine and display the employees gross pay.
Enter hours worked (-1 to end): 39
Enter hourly rate of the worker ($00.00): 10.00
Salary is $390.00
Enter hours worked (-1 to end): 40
Enter hourly rate of the worker ($00.00): 10.00
Salary is $400.00
Enter hours worked (-1 to end): 41
Enter hourly rate of the worker ($00.00): 10.00
Salary is $415.00
Enter hours worked (-1 to end): -1

ANS:

Top:

Determine the gross pay for an arbitrary number of employees


First refinement:
Input the hours worked for the current worker
Input the hourly rate of the current worker
Calculate and display workers gross pay
Process the next worker
Second refinement:
Prompt the user for the hours worked for the rst employee
Input the hours worked for the rst employee
While the sentinel value (-1) has not been entered for the hours
Prompt the user for the employees hourly rate
Input the employees hourly rate
If the hours input is less than or equal to 40
Calculate gross pay by multiplying hours worked by hourly rate
Else
Calculate gross pay by multiplying hours worked above forty by 1.5 times
the hourly rate and adding 40 hours worked by the hourly rate
Display the employees gross pay.
Input the hours worked for the next employee
1
2
3
4
5
6

// Exercise 4.16 Solution: Wages.h


// Definition of class Wages that calculates wages.
// Member functions are defined in Wages.cpp
// Wages class definition
class Wages

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

18

Chapter 4 Control Statements: Part 1

7
8
9
10

{
public:
void calculateWages(); // function to calculate wage
}; // end class Wages

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

// Exercise 4.16 Solution: Wages.cpp


// Member-function definitions for class Wages that calculates wages.
#include <iostream>
using std::cin;
using std::cout;
using std::fixed;
#include <iomanip> // parameterized stream manipulators
using std::setprecision; // sets numeric output precision
#include "Wages.h" // include definition of class Wages from Wages.h
// function to calculate wages
void Wages::calculateWages()
{
double hours; // total hours worked
double rate; // hourly pay rate
double salary; // gross pay
// processing phase
// get first employee's hours worked
cout << "Enter hours worked (-1 to end): ";
cin >> hours;
// set floating-point number format
cout << fixed << setprecision( 2 );
// loop until sentinel value read from user
while ( hours != -1.0 )
{
// get hourly rate
cout << "Enter hourly rate of the worker ($00.00): ";
cin >> rate;
// if employee worked less than 40 hours
if ( hours <= 40 )
salary = hours * rate;
else // else, compute "time-and-a-half" pay
salary = 40.0 * rate + ( hours - 40.0 ) * rate * 1.5;
cout << "Salary is $" << salary; // display gross pay
// prompt for next employee's data
cout << "\n\nEnter hours worked (-1 to end): ";
cin >> hours;
} // end while
} // end function calculateWages

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

19
1
2
3
4
5
6
7
8
9
10

Chapter 4 Control Statements: Part 1

// Exercise 4.16 Solution: ex04_16.cpp


// Create Wages object and invoke its calculateWages function.
#include "Wages.h" // include definition of class Wages from Wages.h
int main()
{
Wages myWages; // create Wages object myWages
myWages.calculateWages(); // call its calculateWages function
return 0; // indicate program ended successfully
} // end main

Enter hours worked (-1 to end): 39


Enter hourly rate of the worker ($00.00): 10.00
Salary is $390.00
Enter hours worked (-1 to end): 40
Enter hourly rate of the worker ($00.00): 10.00
Salary is $400.00
Enter hours worked (-1 to end): 41
Enter hourly rate of the worker ($00.00): 10.00
Salary is $415.00
Enter hours worked (-1 to end): -1

4.17 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 pseudocode program, then 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:
number:
largest:

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).
The current number input to the program.
The largest number found so far.

ANS:

1
2
3
4
5
6
7
8
9
10

// Exercise 4.17 Solution: Largest.h


// Definition of class Largest that finds largest number.
// Member functions are defined in Largest.cpp
// Largest class definition
class Largest
{
public:
void findLargest(); // function to find largest number
}; // end class Largest

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

// Exercise 4.17 Solution: Largest.cpp


// Member-function definitions for class Largest that finds
// the largest number.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

1
2
3
4
5
6
7
8
9
10

// Exercise 4.17 Solution: ex04_17.cpp


// Create Largest object and invoke its findLargest function.
#include "Largest.h" // include definition of class Largest

20

#include "Largest.h" // include definition of class Largest


// function to find the largest number
void Largest::findLargest()
{
int counter = 0; // counter for 10 repetitions
int number; // current number input
int largest; // largest number found so far
cout << "Enter the first number: "; // prompt for first number
cin >> largest; // get first number
while ( ++counter < 10 ) // loop 10 times
{
cout << "Enter the next number : "; // prompt for next input
cin >> number; // get next number
// if current number input is greater than largest number,
// update largest
if ( number > largest )
largest = number;
} // end while
cout << "Largest is " << largest << endl; // display largest number
} // end function findLargest

int main()
{
Largest myLargest; // create Largest object myLargest
myLargest.findLargest(); // call its findLargest function
return 0; // indicate program ended successfully
} // end main

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

21

Chapter 4 Control Statements: Part 1

Enter the first number:


Enter the next number :
Enter the next number :
Enter the next number :
Enter the next number :
Enter the next number :
Enter the next number :
Enter the next number :
Enter the next number :
Enter the next number :
Largest is 345

12
123
56
9
30
35
28
345
47
90

4.18 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
2
3
4
5

10
20
30
40
50

100
200
300
400
500

1000
2000
3000
4000
5000

ANS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

// Exercise 4.18 Solution: ex04_18.cpp


// Print table of values with counter-controlled repetition.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int n = 0;
// display table headers with tabbing
cout << "N\t10*N\t100*N\t1000*N\n\n";
while ( ++n <= 5 ) // loop 5 times
{
// calculate and display table values
cout << n << '\t' << 10 * n << '\t' << 100 * n
<< '\t' << 1000 * n << '\n';
} // end while
cout << endl;
return 0; // indicate program ended successfully
} // end main

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises

10*N

100*N

1000*N

1
2
3
4
5

10
20
30
40
50

100
200
300
400
500

1000
2000
3000
4000
5000

22

4.19 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.]
ANS:

1
2
3
4
5
6
7
8
9
10
11

//
//
//
//

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

// Exercise 4.19 Solution: TwoLargest.cpp


// Member-function definitions for class TwoLargest that finds
// two largest numbers.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

Exercise 4.19 Solution: TwoLargest.h


Definition of class TwoLargest that finds the largest and
second largest numbers.
Member functions are defined in TwoLargest.cpp

// TwoLargest class definition


class TwoLargest
{
public:
void findTwoLargest(); // function to find two largest numbers
}; // end class TwoLargest

#include "TwoLargest.h" // include definition of class TwoLargest


// function to find the two largest numbers
void TwoLargest::findTwoLargest()
{
int counter = 0; // counter for 10 repetitions
int number; // current number input
int largest; // largest number found
int secondLargest; // second largest number found
cout << "Enter the first number: "; // prompt for first number
cin >> largest; // get first number
cout << "Enter next number: "; // prompt for second number
cin >> number; // get second number
// compare second number with first number
if ( number > largest )
{

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

23
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
1
2
3
4
5
6
7
8
9
10

Chapter 4 Control Statements: Part 1

secondLargest = largest;
largest = number;
} // end if
else
secondLargest = number;
counter = 2; // set counter
// get rest of the numbers and find the largest and secondLargest
while ( counter < 10 )
{
cout << "Enter next number: "; // prompt for next number
cin >> number; // get next number
// compare current number with largest and secondLargest
if ( number > largest )
{
secondLargest = largest;
largest = number;
} // end if
else if ( number > secondLargest )
secondLargest = number;
counter++; // increment counter
} // end while
// display largest two numbers
cout << "\nLargest is " << largest
<< "\nSecond largest is " << secondLargest << endl;
} // end function findTwoLargest

// Exercise 4.19 Solution: ex04_19.cpp


// Create TwoLargest object and invoke its findTwoLargest function.
#include "TwoLargest.h" // include definition of class TwoLargest
int main()
{
TwoLargest myTwoLargest; // create TwoLargest object myTwoLargest
myTwoLargest.findTwoLargest(); // call its findTwoLargest function
return 0; // indicate program ended successfully
} // end main

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises

Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter

24

the first number: 12


next number: 123
next number: 56
next number: 9
next number: 30
next number: 35
next number: 28
next number: 345
next number: 47
next number: 90

Largest is 345
Second largest is 123

4.20 The examination-results program of Fig. 4.16Fig. 4.18 assumes that any value input by
the user that is not a 1 must be a 2. Modify 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.
ANS:

1
2
3
4
5
6
7
8
9
10

// Exercise 4.20 Solution: Analysis.h


// Definition of class Analysis that analyzes examination results.
// Member function is defined in Analysis.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

// Exercise 4.20 Solution: Analysis.cpp


// Member-function definitions for class Analysis that
// analyzes examination results.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;

// Analysis class definition


class Analysis
{
public:
void processExamResults(); // process 10 students' examination results
}; // end class Analysis

#include "Analysis.h" // include definition of class Analysis


// process the examination results of 10 students
void Analysis::processExamResults()
{
// initializing variables in declarations
int passes = 0; // number of passes
int failures = 0; // number of failures
int studentCounter = 1; // student counter
int result; // one exam result (1 = pass, 2 = fail)
bool validInput = false; // false until valid input entered
// process 10 students using counter-controlled loop

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

25
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
1
2
3
4
5
6
7

Chapter 4 Control Statements: Part 1

while ( studentCounter <= 10 )


{
// prompt user for input and obtain value from user
cout << "Enter result (1 = pass, 2 = fail): ";
cin >> result; // input result
if ( result == 1 ) // 1 is a valid input
validInput = true;
if ( result == 2 ) // 2 is a valid input
validInput = true;
// loop until valid input
while ( validInput == false )
{
cout << "Invalid result"
<< "\nEnter result (1=pass, 2=fail): ";
cin >> result;
if ( result == 1 ) // 1 is a valid input
validInput = true;
if ( result == 2 ) // 2 is a valid input
validInput = true;
} // end while
// if...else nested in while
if ( result == 1 ) // if result 1,
passes = passes + 1; // increment passes;
else // else result is not 1, so
failures = failures + 1; // increment failures
// increment studentCounter so loop eventually terminates
studentCounter = studentCounter + 1;
validInput = false; // reset for next input
} // end while
// termination phase; display number of passes and failures
cout << "Passed " << passes << "\nFailed " << failures << endl;
// determine whether more than eight students passed
if ( passes > 8 )
cout << "Raise tuition " << endl;
} // end function processExamResults

// Exercise 4.20 Solution: ex04_20.cpp


// Test program for class Analysis.
#include "Analysis.h" // include definition of class Analysis
int main()
{
Analysis application; // create Analysis object

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
8
9
10

26

application.processExamResults(); // call function to process results


return 0; // indicate successful termination
} // end main

Enter result (1
Enter result (1
Enter result (1
Enter result (1
Enter result (1
Invalid result
Enter result (1
Enter result (1
Enter result (1
Enter result (1
Invalid result
Enter result (1
Enter result (1
Invalid result
Enter result (1
Enter result (1
Passed 7
Failed 3

=
=
=
=
=

pass,
pass,
pass,
pass,
pass,

2
2
2
2
2

=
=
=
=
=

fail):
fail):
fail):
fail):
fail):

1
1
2
1
3

=
=
=
=

pass,
pass,
pass,
pass,

2
2
2
2

=
=
=
=

fail):
fail):
fail):
fail):

2
1
1
4

= pass, 2 = fail): 2
= pass, 2 = fail): 0
= pass, 2 = fail): 1
= pass, 2 = fail): 1

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

27

Chapter 4 Control Statements: Part 1

4.21

What does the following program print?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

// Exercise 4.21: ex04_21.cpp


// What does this program print?
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int count = 1; // initialize count
while ( count <= 10 ) // loop 10 times
{
// output line of text
cout << ( count % 2 ? "****" : "++++++++" ) << endl;
count++; // increment count
} // end while
return 0; // indicate successful termination
} // end main

ANS:

****
++++++++
****
++++++++
****
++++++++
****
++++++++
****
++++++++

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
4.22
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

28

What does the following program print?

// Exercise 4.22: ex04_22.cpp


// What does this program print?
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int row = 10; // initialize row
int column; // declare column
while ( row >= 1 ) // loop until row < 1
{
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
return 0; // indicate successful termination
} // end main
ANS:

>>>>>>>>>>
<<<<<<<<<<
>>>>>>>>>>
<<<<<<<<<<
>>>>>>>>>>
<<<<<<<<<<
>>>>>>>>>>
<<<<<<<<<<
>>>>>>>>>>
<<<<<<<<<<

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. Note that 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, the programmer 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 have learned.]

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

29

Chapter 4 Control Statements: Part 1


a)

if ( x < 10 )
if ( y > 10 )
cout << "*****" << endl;
else
cout << "#####" << endl;

b)

cout << "$$$$$" << endl;


if ( x < 10 )
{
if ( y > 10 )
cout << "*****" << endl;
}
else
{
cout << "#####" << endl;
cout << "$$$$$" << endl;
}

ANS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

// Exercise 4.23 Solution: ex04_23.cpp


// Dangling-else problem.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
// part
int x =
int y =
cout <<

A, x=9 and y=11


9;
11;
"Output for part A, x=9 and y=11:" << endl;

if ( x < 10 )
if ( y > 10 )
cout << "*****" << endl;
else
cout << "#####" << endl;
cout << "$$$$$" << endl;
// part A, x=11 and y=9
x = 11;
y = 9;
cout << endl << "Output for part A, x=11 and y=9:" << endl;
if ( x < 10 )
if ( y > 10 )
cout << "*****" << endl;
else
cout << "#####" << endl;
cout << "$$$$$" << endl;

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

30

// part B, x=9 and y=11


x = 9;
y = 11;
cout << endl << "Output for part B, x=9 and y=11:" << endl;
if ( x < 10 )
{
if ( y > 10 )
cout << "*****" << endl;
} // end outer if
else
{
cout << "#####" << endl;
cout << "$$$$$" << endl;
} // end else
// part B, x=11 and y=9
x = 11;
y = 9;
cout << endl << "Output for part B, x=11 and y=9:" << endl;
if ( x < 10 )
{
if ( y > 10 )
cout << "*****" << endl;
} // end outer if
else
{
cout << "#####" << endl;
cout << "$$$$$" << endl;
} // end else
return 0; // indicate successful termination
} // end main

Output for part A, x=9 and y=11:


*****
$$$$$
Output for part A, x=11 and y=9:
$$$$$
Output for part B, x=9 and y=11:
*****
Output for part B, x=11 and y=9:
#####
$$$$$

4.24 (Another Dangling-Else Problem) Modify 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 is possible that no modification is necessary.]

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

31

Chapter 4 Control Statements: Part 1


if (
if (
cout
else
cout
cout
cout

y == 8 )
x == 5 )
<< "@@@@@" << endl;
<< "#####" << endl;
<< "$$$$$" << endl;
<< "&&&&&" << endl;

a) Assuming x

= 5

and y

= 8,

the following output is produced.

b) Assuming x

= 5

and y

= 8,

the following output is produced.

c) Assuming x

= 5

and y

= 8,

the following output is produced.

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

@@@@@

@@@@@
&&&&&

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.]
#####
$$$$$
&&&&&

ANS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

// Exercise 4.24 Solution: ex04_24.cpp


// Dangling-else problem.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int x = 5; // initialize x to 5
int y = 8; // initialize y to 8
// part a
if ( y == 8 )
{
if ( x == 5 )

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70

cout << "@@@@@" << endl;


else
cout << "#####" << endl;
} // end if
cout << "$$$$$" << endl;
cout << "&&&&&" << endl << endl;
// part b
if ( y == 8 )
{
if ( x == 5 )
cout << "@@@@@" <<
else
{
cout << "#####" <<
cout << "$$$$$" <<
cout << "&&&&&" <<
} // end inner else
} // end outer if

endl;
endl;
endl;
endl;

cout << endl;


// part c
if ( y == 8 )
{
if ( x == 5 )
cout << "@@@@@" << endl;
else
{
cout << "#####" << endl;
cout << "$$$$$" << endl;
} // end inner else
} // end outer if
cout << "&&&&&" << endl << endl;
// part d
y = 7;
if ( y == 8 )
{
if ( x == 5 )
cout << "@@@@@"
} // end if
else
{
cout << "#####" <<
cout << "$$$$$" <<
cout << "&&&&&" <<
} // end else

<< endl;

endl;
endl;
endl;

return 0; // indicate successful termination


} // end main

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

32

33

Chapter 4 Control Statements: Part 1

4.25 Write a program that reads in the size of the side of a square and then prints 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
*****
*
*
*
*
*
*
*****

ANS:

1
2
3
4
5
6
7
8
9
10

// Exercise 4.25 Solution: Square.h


// Definition of class Square.
// Member function is defined in Square.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

// Exercise 4.25 Solution: Square.cpp


// Member-function definitions for class Square.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

// Square class definition


class Square
{
public:
void drawSquare(); // draw a hollow square
}; // end class Square

#include "Square.h" // include definition of class Square


// draw a hollow square surrounded by stars
void Square::drawSquare()
{
int stars; // number of stars on a side
int column; // the current column of the square being printed
int row = 1; // the current row of the square being printed
// prompt and read the length of the side from the user
cout << "Enter length of side:";
cin >> stars;
// valid input, if invalid, set to default
if ( stars < 1 )
{
stars = 1;
cout << "Invalid Input\nUsing default value 1\n";
} // end if
else if ( stars > 20 )
{

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
1
2
3
4
5
6
7
8
9
10

stars = 20;
cout << "Invalid Input\nUsing default value 20\n";
} // end else if
// repeat for as many rows as the user entered
while ( row <= stars )
{
column = 1;
// and for as many columns as rows
while ( column <= stars )
{
if ( row == 1 )
cout << "*";
else if ( row == stars )
cout << "*";
else if ( column == 1 )
cout << "*";
else if ( column == stars )
cout << "*";
else
cout << " ";
column++; // increment column
} // end inner while
cout << endl;
row++; // increment row
} // end outer while
} // end function drawSquare

// Exercise 4.25 Solution: ex04_25.cpp


// Test program for class Square.
#include "Square.h" // include definition of class Square
int main()
{
Square application; // create Square object
application.drawSquare(); // call function to draw square
return 0; // indicate successful termination
} // end main

Enter length of side:5


*****
*
*
*
*
*
*
*****

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

34

35

Chapter 4 Control Statements: Part 1

4.26 A palindrome is a number or a text phrase that reads the same backwards as forwards. For
example, each of the following five-digit integers is a palindrome: 12321, 55555, 45554 and 11611.
Write a program that reads in a five-digit integer and determines whether it is a palindrome. [Hint:
Use the division and modulus operators to separate the number into its individual digits.]
ANS:

1
2
3
4
5
6
7
8
9
10

// Exercise 4.26 Solution: Palindrome.h


// Definition of class Palindrome.
// Member function is defined in Palindrome.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

// Exercise 4.26 Solution: Palindrome.cpp


// Member-function definitions for class Palindrome.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

// Palindrome class definition


class Palindrome
{
public:
void checkPalindrome(); // checks if a number is a palindrome
}; // end class Palindrome

#include "Palindrome.h" // include definition of class Palindrome


// check if a 5-digit number is a Palindrome
void Palindrome::checkPalindrome()
{
int number = 0; // user input number
int digit1; // first digit
int digit2; // second digit
int digit4; // fourth digit; dont care about third digit
int digit5; // fifth digit
int digits = 0; // number of digits in input
// ask for a number until it is five digits
while ( digits != 5 )
{
cout << "Enter a 5-digit number: "; // prompt for a number
cin >> number; // get number
// verify if number has 5 digits
if ( number < 100000 )
{
if ( number > 9999 )
digits = 5;
else
cout << "Number must be 5 digits" << endl;
} // end if
else
cout << "Number must be 5 digits" << endl;

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
1
2
3
4
5
6
7
8
9
10

36

} // end while
// get
digit1
digit2
digit4
digit5

the digits
= number /
= number %
= number %
= number %

10000;
10000 / 1000;
10000 % 1000 % 100 / 10;
10000 % 1000 % 100 % 10;

// print whether the number is a palindrome


if ( digit1 == digit5 )
{
if ( digit2 == digit4 )
cout << number << " is a palindrome!!!" << endl;
else
cout << number << " is not a palindrome." << endl;
}
else
cout << number << " is not a palindrome." << endl;
} // end function checkPalindrome

// Exercise 4.26 Solution: ex04_26.cpp


// Test program for class Palindrome.
#include "Palindrome.h" // include definition of class Palindrome
int main()
{
Palindrome application; // create Palindrome object
application.checkPalindrome(); // call function to check palindrome
return 0; // indicate successful termination
} // end main

Enter a 5-digit number: 12321


12321 is a palindrome!!!

Enter a 5-digit number: 12345


12345 is not a palindrome.

4.27 Input an integer containing only 0s and 1s (i.e., a binary integer) and print its decimal
equivalent. Use the modulus and division operators to pick off the binary numbers digits one at
a time from right to left. Much as in the decimal number system, where the rightmost digit has a
positional value of 1, the next digit left has a positional value of 10, then 100, then 1000, and so on,
in the binary number system the rightmost digit has a positional value of 1, the next digit left has a
positional value of 2, then 4, then 8, and so on. Thus the decimal number 234 can be interpreted

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

37

Chapter 4 Control Statements: Part 1

as 2 * 100 + 3 * 10 + 4 * 1. The decimal equivalent of binary 1101 is 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8 or


1 + 0 + 4 + 8, or 13. [Note: The reader not familiar with binary numbers might wish to refer to
Appendix D.]
ANS:

1
2
3
4
5
6
7
8
9
10

// Exercise 4.27 Solution: Binary.h


// Definition of class Binary.
// Member function is defined in Binary.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

// Exercise 4.27 Solution: Binary.cpp


// Member-function definitions for class Binary.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

1
2
3
4

// Binary class definition


class Binary
{
public:
void convertToDecimal(); // convert binary to decimal
}; // end class Binary

#include "Binary.h" // include definition of class Binary


// convert a binary number to a decimal number
void Binary::convertToDecimal()
{
int binary; // binary value
int bit = 1; // bit positional value
int decimal = 0; // decimal value
// prompt for and read in a binary number
cout << "Enter a binary number: ";
cin >> binary;
// convert to decimal equivalent
while ( binary != 0 )
{
decimal += binary % 10 * bit;
binary /= 10;
bit *= 2;
} // end while loop
cout << "Decimal is: " << decimal << endl;
} // end function convertToDecimal

// Exercise 4.27 Solution: ex04_27.cpp


// Test program for class Binary.
#include "Binary.h" // include definition of class Binary

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
5
6
7
8
9
10

38

int main()
{
Binary application; // create Binary object
application.convertToDecimal(); // function to convert to decimal
return 0; // indicate successful termination
} // end main

Enter a binary number: 1001001


Decimal is: 73

4.28 Write a program that displays the checkerboard pattern shown below. Your program must
use only three output statements, one of each of the following forms:
cout << "* ";
cout << ' ';
cout << endl;

* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *

ANS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

// Exercise 4.28 Solution: ex04_28.cpp


// Prints out an 8 x 8 checkerboard pattern.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int row = 8; // row counter
int side; // side counter
while ( row-- > 0 ) // loop 8 times
{
side = 8; // reset side counter
// if even row, begin with a space
if ( row % 2 == 0 )
cout << ' ';
while ( side-- > 0 ) // loop 8 times
cout << "* ";
cout << endl; // go to next line

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

39
24
25
26
27
28

Chapter 4 Control Statements: Part 1

} // end while
cout << endl;
return 0; // indicate successful termination
} // end main

* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *

4.29 Write a program that prints the powers of the integer 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?
ANS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

// Exercise 4.29 Solution: ex04_29.cpp


// Program creates an infinite loop.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int x = 1;
while ( true ) // infinite loop
{
x *= 2;
cout << x << endl;
} // end while
return 0; // indicate successful termination
} // end main

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises

40

2
4
...
32768
65536
131072
262144
524288
1048576
2097152
4194304
8388608
16777216
33554432
67108864
134217728
268435456
536870912
1073741824
-2147483648
0

4.30 Write a program that reads the radius of a circle (as a double value) and computes and prints
the diameter, the circumference and the area. Use the value 3.14159 for .
ANS:

1
2
3
4
5
6
7
8
9
10

// Exercise 4.30 Solution: Circle.h


// Definition of class Circle.
// Member function is defined in Circle.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14

// Exercise 4.30 Solution: Circle.cpp


// Member-function definitions for class Circle.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

// Circle class definition


class Circle
{
public:
void calculate(); // calculate diameter, circumference and area
}; // end class Circle

#include "Circle.h" // include definition of class Circle


// calculate diameter, circumference and area of a circle
void Circle::calculate()
{
double radius; // input radius
double pi = 3.14159; // value for pi

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

41
15
16
17
18
19
20
21
22
23
24
25
26
27
28
1
2
3
4
5
6
7
8
9
10

Chapter 4 Control Statements: Part 1

// get radius value


cout << "Enter the radius: ";
cin >> radius;
// compute and display diameter
cout << "The diameter is " << radius * 2.0;
// compute and display circumference
cout << "\nThe circumference is " << 2.0 * pi * radius;
// compute and display area
cout << "\nThe area is " << pi * radius * radius << endl;
} // end function calculate

// Exercise 4.30 Solution: ex04_30.cpp


// Test program for class Circle.
#include "Circle.h" // include definition of class Circle
int main()
{
Circle application; // create Circle object
application.calculate(); // function to calculate
return 0; // indicate successful termination
} // end main

Enter the radius: 25


The diameter is 50
The circumference is 157.08
The area is 1963.49

4.31 What is wrong with the following statement? Provide the correct statement to accomplish
what the programmer was probably trying to do.
cout << ++( x + y );

ANS: The ++ operator must be used in conjuction with variables. The programmer proba-

bly intended to write the statement:

cout << x + y + 1;.

4.32 Write a program that reads three nonzero double values and determines and prints whether
they could represent the sides of a triangle.
ANS:

1
2
3
4
5
6
7
8

// Exercise 4.32 Solution: Triangle1.h


// Definition of class Triangle1.
// Member function is defined in Triangle1.cpp
// Triangle1 class definition
class Triangle1
{
public:

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
9
10

void checkSides(); // checks if three sides can form a triangle


}; // end class Triangle1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

// Exercise 4.32 Solution: Triangle1.cpp


// Member-function definitions for class Triangle1.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

1
2
3
4

#include "Triangle1.h" // include definition of class Triangle1


// checks if three sides can form a triangle
void Triangle1::checkSides()
{
double side1; // length of side 1
double side2; // length of side 2
double side3; // length of side 3
bool isTriangle = false; // whether the sides can form a triangle
// get values of three sides
cout << "Enter side 1: ";
cin >> side1;
cout << "Enter side 2: ";
cin >> side2;
cout << "Enter side 3: ";
cin >> side3;
// test if the sides can form a triangle
if ( side1 + side2 > side3 )
{
if ( side2 + side3 > side1 )
{
if ( side3 + side1 > side2 )
isTriangle = true;
} // end inner if
} // end outer if
// display result
if ( isTriangle )
cout << "These could be sides to a triangle." << endl;
else
cout << "These do not form a triangle." << endl;
} // end function checkSides

// Exercise 4.32 Solution: ex04_32.cpp


// Test program for class Triangle1.
#include "Triangle1.h" // include definition of class Triangle1

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

42

43
5
6
7
8
9
10

Chapter 4 Control Statements: Part 1

int main()
{
Triangle1 application; // create Triangle1 object
application.checkSides(); // function to check three sides
return 0; // indicate successful termination
} // end main

Enter
Enter
Enter
These

side 1: 3
side 2: 4
side 3: 5
could be sides to a triangle.

4.33 Write a program that reads three nonzero integers and determines and prints whether they
could be the sides of a right triangle.
ANS:

1
2
3
4
5
6
7
8
9
10

// Exercise 4.33 Solution: Triangle2.h


// Definition of class Triangle2.
// Member function is defined in Triangle2.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

// Exercise 4.33 Solution: Triangle2.cpp


// Member-function definitions for class Triangle2.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

// Triangle2 class definition


class Triangle2
{
public:
void checkSides(); // checks if three sides can form a right triangle
}; // end class Triangle2

#include "Triangle2.h" // include definition of class Triangle2


// checks if three sides can form a triangle
void Triangle2::checkSides()
{
int side1; // length of side 1
int side2; // length of side 2
int side3; // length of side 3
bool isRightTriangle = false; // if sides can form right triangle
// get values of three sides
cout << "Enter side 1: ";
cin >> side1;
cout << "Enter side 2: ";
cin >> side2;

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
1
2
3
4
5
6
7
8
9
10

44

cout << "Enter side 3: ";


cin >> side3;
// square the sides
int side1Square = side1 * side1;
int side2Square = side2 * side2;
int side3Square = side3 * side3;
// test if sides can form a right triangle
if ( ( side1Square + side2Square ) == side3Square )
isRightTriangle = true;
else if ( ( side1Square + side3Square ) == side2Square )
isRightTriangle = true;
else if ( ( side2Square + side3Square ) == side1Square )
isRightTriangle = true;
// display results
if ( isRightTriangle )
cout << "These are the sides of a right triangle." << endl;
else
cout << "These do not form a right triangle." << endl;
} // end function checkSides

// Exercise 4.33 Solution: ex04_33.cpp


// Test program for class Triangle2.
#include "Triangle2.h" // include definition of class Triangle2
int main()
{
Triangle2 application; // create Triangle2 object
application.checkSides(); // function to check three sides
return 0; // indicate successful termination
} // end main

Enter
Enter
Enter
These

side 1:
side 2:
side 3:
are the

3
4
5
sides of a right triangle.

4.34 (Cryptography) A company wants to transmit data over the telephone, but is concerned that
its phones could be tapped. All of the data are transmitted as four-digit integers. The company has
asked you to write a program that encrypts the data so that it can be transmitted more securely. Your
program should read a four-digit integer and encrypt it as follows: Replace each digit by (the sum of
that digit plus 7) modulus 10. Then, swap the first digit with the third, swap the second digit with
the fourth and print the encrypted integer. Write a separate program that inputs an encrypted fourdigit integer and decrypts it to form the original number.
ANS:

1
2

// Exercise 4.34 Part A Solution: Encrypt.h


// Definition of class Encrypt.

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

45

Chapter 4 Control Statements: Part 1

3
4
5
6
7
8
9
10

// Member function is defined in Encrypt.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

// Exercise 4.34 Part A Solution: Encrypt.cpp


// Member-function definitions for class Encrypt.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

1
2
3
4
5
6
7

// Encrypt class definition


class Encrypt
{
public:
void encrypt(); // encrypt a four-digit number
}; // end class Encrypt

#include "Encrypt.h" // include definition of class Encrypt


// encrypt a four-digit number
void Encrypt::encrypt()
{
int number; // original number
int digit1; // first digit
int digit2; // second digit
int digit3; // third digit
int digit4; // fourth digit
int encryptedNumber; // encrypted number
// enter four-digit number to be encrypted
cout << "Enter a four-digit number: ";
cin >> number;
// encrypt
digit1 = (
digit2 = (
digit3 = (
digit4 = (

number
number
number
number

/
%
%
%

1000 + 7 )
1000 / 100
100 / 10 +
10 + 7 ) %

% 10;
+ 7 ) % 10;
7 ) % 10;
10;

encryptedNumber =
digit1 * 10 + digit2 + digit3 * 1000 + digit4 * 100;
cout << "Encrypted number is " << encryptedNumber << endl;
} // end function encrypt

// Exercise 4.34 Part A Solution: ex04_34.cpp


// Test program for class Encrypt.
#include "Encrypt.h" // include definition of class Encrypt
int main()
{
Encrypt application; // create Encrypt object

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
8
9
10

application.encrypt(); // function to encrypt a four-digit number


return 0; // indicate successful termination
} // end main

Enter a four-digit number: 1234


Encrypted number is 189

1
2
3
4
5
6
7
8
9
10

// Exercise 4.34 Part B Solution: Decrypt.h


// Definition of class Decrypt.
// Member function is defined in Decrypt.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

// Exercise 4.34 Part B Solution: Decrypt.cpp


// Member-function definitions for class Decrypt.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

// Decrypt class definition


class Decrypt
{
public:
void decrypt(); // decrypt a four-digit number
}; // end class Decrypt

#include "Decrypt.h" // include definition of class Decrypt


// decrypt a number
void Decrypt::decrypt()
{
int number; // original number
int digit1; // first digit
int digit2; // second digit
int digit3; // third digit
int digit4; // fourth digit
int decryptedNumber; // encrypted number
// enter an encrypted number to be decrypted
cout << "Enter an encrypted number: ";
cin >> number;
// decrypt
digit1 = (
digit2 = (
digit3 = (
digit4 = (

number
number
number
number

/
%
%
%

1000 + 3 )
1000 / 100
100 / 10 +
10 + 3 ) %

% 10;
+ 3 ) % 10;
3 ) % 10;
10;

decryptedNumber =
digit1 * 10 + digit2 + digit3 * 1000 + digit4

* 100;

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

46

47

Chapter 4 Control Statements: Part 1

33
34

cout << "Decrypted number is " << decryptedNumber << endl;


} // end function decrypt

1
2
3
4
5
6
7
8
9
10

// Exercise 4.34 Part B Solution: ex04_34.cpp


// Test program for class Decrypt.
#include "Decrypt.h" // include definition of class Decrypt
int main()
{
Decrypt application; // create Decrypt object
application.decrypt(); // function to decrypt an encrypted number
return 0; // indicate successful termination
} // end main

Enter an encrypted number: 189


Decrypted number is 1234

4.35 The factorial of a nonnegative integer 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 to 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:
a) Write a program that reads a nonnegative integer and computes and prints its factorial.
ANS:

1
2
3
4
5
6
7
8
9
10

// Exercise 4.35 Part A Solution: Factorial.h


// Definition of class Factorial.
// Member function is defined in Factorial.cpp

1
2
3
4
5
6
7
8
9
10
11

// Exercise 4.35 Part A Solution: Factorial.cpp


// Member-function definitions for class Factorial.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

// Factorial class definition


class Factorial
{
public:
void calculateFactorial(); // calculates the factorial of a number
}; // end class Factorial

#include "Factorial.h" // include definition of class Factorial


// calculate factorial
void Factorial::calculateFactorial()

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

1
2
3
4
5
6
7
8
9
10

// Exercise 4.35 Part A Solution: ex04_35.cpp


// Test program for class Factorial.
#include "Factorial.h" // include definition of class Factorial

48

int number; // user input


int factorial = 1; // factorial of input value
// get input
cout << "Enter a positive Integer: ";
cin >> number;
cout << number << "! is ";
while ( number > 0 ) // calculate factorial
{
factorial *= number;
number--;
} // end while

cout << factorial << endl;


} // end function calculateFactorial

int main()
{
Factorial application; // create Factorial object
application.calculateFactorial(); // function to calculate factorial
return 0; // indicate successful termination
} // end main

Enter a positive Integer: 5


5! is 120

b) Write a program that estimates the value of the mathematical constant e by using the
formula:
1 1 1
e = 1 + ----- + ----- + ----- +
1! 2! 3!

Prompt the user for the desired accuracy of e (i.e., the number of terms in the summation).
ANS:

1
2
3
4
5
6
7
8

// Exercise 4.35 Part B Solution: E.h


// Definition of class E.
// Member function is defined in E.cpp
// E class definition
class E
{
public:

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

49

Chapter 4 Control Statements: Part 1

9
10

void approximate(); // approximates the value of E


}; // end class E

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

// Exercise 4.35 Part B Solution: E.cpp


// Member-function definitions for class E.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

1
2
3
4
5
6
7
8
9
10

// Exercise 4.35 Part B Solution: ex04_35.cpp


// Test program for class E.
#include "E.h" // include definition of class E from E.h

#include "E.h" // include definition of class E from E.h


// approximates the value of E
void E::approximate()
{
int number = 1; // counter
int accuracy; // accuracy of estimate
int factorial = 1; // value of factorial
double e = 1.0; // estimate value of e
// get accuracy
cout << "Enter desired accuracy of e: ";
cin >> accuracy;
// calculate estimation
while ( number < accuracy )
{
factorial *= number;
e += 1.0 / factorial;
number++;
} // end while
cout << "e is " << e << endl;
} // end function approximate

int main()
{
E application; // create E object
application.approximate(); // function to approximates the value of E
return 0; // indicate successful termination
} // end main

Enter desired accuracy of e: 10


e is 2.71828

c) Write a program that computes the value of ex by using the formula

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises
2

50

x
x x x
e = 1 + ----- + ----- + ----- +
1! 2! 3!

Prompt the user for the desired accuracy of e (i.e., the number of terms in the summation).
ANS:

1
2
3
4
5
6
7
8
9
10

// Exercise 4.35 Part C Solution: EtoX.h


// Definition of class EtoX.
// Member function is defined in EtoX.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

// Exercise 4.35 Part C Solution: EtoX.cpp


// Member-function definitions for class EtoX.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

// EtoX class definition


class EtoX
{
public:
void approximate(); // approximates the value of E to the X
}; // end class EtoX

#include "EtoX.h" // include definition of class EtoX from EtoX.h


// approximates the value of E to the X
void EtoX::approximate()
{
int number = 1; // counter
int accuracy; // accuracy of estimate
int factorial = 1; // value of factorial
int x; // x value
double e = 1.0; // estimate value of e
double exponent = 1.0; // exponent value
cout << "Enter exponent: ";
cin >> x;
cout << "Enter desired accuracy of e: ";
cin >> accuracy;
// calculate estimation
while ( number < accuracy )
{
exponent *= x; // calculate value of x to current exponent
factorial *= number; // calculate factorial for current accuracy
e += exponent / factorial; // calculate e for current accuracy
number++;
} // end while
cout << "e to the " << x << " is " << e << endl;
} // end function approximate

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

51
1
2
3
4
5
6
7
8
9
10

Chapter 4 Control Statements: Part 1

// Exercise 4.35 Part C Solution: ex04_35.cpp


// Test program for class EtoX.
#include "EtoX.h" // include definition of class EtoX from EtoX.h
int main()
{
EtoX application; // create EtoX object
application.approximate(); // approximate the value of E to the X
return 0; // indicate successful termination
} // end main

Enter exponent: 10
Enter desired accuracy of e: 10
e to the 10 is 10086.6

4.36 [Note: This exercise corresponds to Section 4.13, a portion of our software engineering case
study.] Describe in 200 words or fewer what an automobile is and does. List the nouns and verbs
separately. In the text, we stated that each noun might correspond to an object that will need to be
built to implement a system, in this case a car. Pick five of the objects you listed, and, for each, list
several attributes and several behaviors. Describe briefly how these objects interact with one another
and other objects in your description. You have just performed several of the key steps in a typical
object-oriented design.
ANS:

A specific type of vehicle containing 4 wheels, doors, seats, windows, steering wheel,
brakes, radio, engine, exhaust system, transmission, axles, windshield, mirrors, etc.
A car can accelerate, decelerate, turn, move forward, move backward, stop, etc.
Wheels:
Attributes: size, type, tread depth.
Behaviors: rotate forward, rotate backward.
Doors:
Attributes: type (passenger, trunk, etc.), open or closed.
Behaviors: open, close, lock, unlock.
Steering Wheel:
Attributes: adjustable.
Behaviors: turn left, turn right, adjust up, adjust down.
Brakes:
Attributes: pressed or not pressed, pressure of press.
Behaviors: press, antilock.
Engine:
Attributes: cylinders, radiator, timing belts, spark plugs, etc.
Behaviors: accelerate, decelerate, turn on, turn off.
Interactions:
Person turns the steering wheel which causes the wheels to turn in the appropriate
direction.
Person presses the accelerator pedal which causes the engine revolutions per minute
to increase, resulting in a faster rotation of the wheels.
Person opens door. Person closes door.
Person releases accelerator pedal which causes engine RPMs to decrease, resulting in
a slower rotation of the wheels.
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Exercises

52

Person presses brake pedal which causes brakes to be applied to wheels slows the rotation of the wheels.

2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.

Você também pode gostar