Escolar Documentos
Profissional Documentos
Cultura Documentos
Control
Statements:
Part 1
Lewis Carroll
OBJECTIVES
In this chapter you will learn:
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Self-Review Exercises
4.1
4.2
Write four different C++ statements that each add 1 to integer variable x.
ANS: x = x + 1;
+= 1;
++x;
x++;
4.3
count
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
b) Set variable x to 1.
ANS: x = 1;
d) Add variable x to variable sum and assign the result to variable sum.
ANS: sum += x;
or
sum = sum + x;
e) Print "The
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
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
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
4
15
16
17
18
19
20
21
22
23
24
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
4.7
or
power = power * x;
f) Postincrement variable i by 1.
ANS: i++;
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
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
4.9
ANS: Error: Missing the closing right brace of the while body.
b)
c)
if ( gender == 1 )
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
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
ANS: The value of the variable z is never changed in the while statement. Therefore, if the
Exercises
4.11
ANS: The semicolon at the end of the if condition should be removed. The closing double
b)
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)
int x = 1, total;
while ( x <= 10 )
{
total += x;
x++;
}
d)
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
ANS: The program prints the squares of the integers from 1 to 10 and the sum of those
squares.
1
2
3
4
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
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
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
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
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
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
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
ANS:
Top:
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
12
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
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
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
13
14
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
//
//
//
//
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
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
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:
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
18
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
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
19
1
2
3
4
5
6
7
8
9
10
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:
ANS:
1
2
3
4
5
6
7
8
9
10
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
1
2
3
4
5
6
7
8
9
10
20
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
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
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
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
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
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
24
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
8
9
10
26
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
4.21
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
>>>>>>>>>>
<<<<<<<<<<
>>>>>>>>>>
<<<<<<<<<<
>>>>>>>>>>
<<<<<<<<<<
>>>>>>>>>>
<<<<<<<<<<
>>>>>>>>>>
<<<<<<<<<<
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
if ( x < 10 )
if ( y > 10 )
cout << "*****" << endl;
else
cout << "#####" << endl;
b)
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
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
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
y == 8 )
x == 5 )
<< "@@@@@" << endl;
<< "#####" << endl;
<< "$$$$$" << endl;
<< "&&&&&" << endl;
a) Assuming x
= 5
and y
= 8,
b) Assuming x
= 5
and y
= 8,
c) Assuming x
= 5
and y
= 8,
@@@@@
$$$$$
&&&&&
@@@@@
@@@@@
&&&&&
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
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
endl;
endl;
endl;
endl;
<< endl;
endl;
endl;
endl;
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
32
33
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
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
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
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
34
35
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
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
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;
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
1
2
3
4
5
6
7
8
9
10
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
1
2
3
4
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
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
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
39
24
25
26
27
28
} // 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
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
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-
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
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
9
10
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
1
2
3
4
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
42
43
5
6
7
8
9
10
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
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
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
45
3
4
5
6
7
8
9
10
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
1
2
3
4
5
6
7
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
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises
8
9
10
1
2
3
4
5
6
7
8
9
10
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
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
33
34
1
2
3
4
5
6
7
8
9
10
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
1
2
3
4
5
6
7
8
9
10
11
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
48
int main()
{
Factorial application; // create Factorial object
application.calculateFactorial(); // function to calculate factorial
return 0; // indicate successful termination
} // end main
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
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
49
9
10
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
1
2
3
4
5
6
7
8
9
10
int main()
{
E application; // create E object
application.approximate(); // function to approximates the value of E
return 0; // indicate successful termination
} // end main
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
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
2006 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
51
1
2
3
4
5
6
7
8
9
10
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.