Absolute C++ (phần 3) - Pdf 17

80 Flow of Control
34. For each of the following situations, tell which type of loop (while, do-while, or for)
would work best.
a. Summing a series, such as
1/2 + 1/3 + 1/4 + 1/5 + . . . + 1/10.
b. Reading in the list of exam scores for one student.
c. Reading in the number of days of sick leave taken by employees in a department.
d. Testing a function to see how it performs for different values of its arguments.
35. What is the output produced by the following? (
x is of type int.)
int x = 10;
while (x > 0)
{
cout << x << endl;
x = x + 3;
}

THE
break
AND
continue
STATEMENTS
In previous subsections, we have described the basic flow of control for the while, do-
while
, and for loops. This is how the loops should normally be used and is the way
they are usually used. However, you can alter the flow of control in two ways, which in
rare cases can be a useful and safe technique. The two ways of altering the flow of con-
trol are to insert a
break or continue statement. The break statement ends the loop.
The
continue statement ends the current iteration of the loop body. The break state-

Loops 81
Display 2.8 A break Statement in a Loop
1 #include <iostream>
2 using namespace std;
3 int main( )
4 {
5 int number, sum = 0, count = 0;
6 cout << "Enter 4 negative numbers:\n";
7 while (++count <= 4)
8 {
9 cin >> number;
10 if (number >= 0)
11 {
12 cout << "ERROR: positive number"
13 << " or zero was entered as the\n"
14 << count << "th number! Input ends "
15 << "with the " << count << "th number.\n"
16 << count << "th number was not added in.\n";
17 break;
18 }
19 sum = sum + number;
20 }
21 cout << sum << " is the sum of the first "
22 << (count - 1) << " numbers.\n";
23 return 0;
24 }
S
AMPLE
D
IALOGUE

S
AMPLE
D
IALOGUE
Enter 4 negative numbers, ONE PER LINE:
1
ERROR: positive number (or zero)!
Reenter that number and continue:
-1
-2
3
ERROR: positive number!
Reenter that number and continue:
-3
-4
-10 is the sum of the 4 numbers.
Chapter Summary 83
Self-Test Exercises
Chapter Summary
Note that you never absolutely need a break or continue statement. The programs
in Displays 2.8 and 2.9 can be rewritten so that neither uses either a
break or continue
statement. The continue statement can be particularly tricky and can make your code
hard to read. It may be best to avoid the
continue statement completely or at least use
it only on rare occasions.

NESTED LOOPS
It is perfectly legal to nest one loop statement inside another loop statement. When
doing so, remember that any

■ A loop can be ended early with a break statement. A single iteration of a loop body
may be ended early with a
continue statement. It is best to use break statements
sparingly. It is best to completely avoid using
continue statements, although some
programmers do use them on rare occasions.
ANSWERS TO SELF-TEST EXERCISES
1. a. true.
b. true. Note that expressions a and b mean exactly the same thing. Because the operators ==
and
< have higher precedence than &&, you do not need to include the parentheses. The
parentheses do, however, make it easier to read. Most people find the expression in a easier
to read than the expression in b, even though they mean the same thing.
c.
true.
d. true.
e. false. Since the value of the first subexpression, (count == 1), is false, you know that
the entire expression is
false without bothering to evaluate the second subexpression.
Thus, it does not matter what the values of
x and y are. This is short-circuit evaluation.
f.
true. Since the value of the first subexpression, (count < 10), is true, you know that the
entire expression is
true without bothering to evaluate the second subexpression. Thus, it
does not matter what the values of
x and y are. This is short-circuit evaluation.
g.
false. Notice that the expression in g includes the expression in f as a subexpression. This
subexpression is evaluated using short-circuit evaluation as we described for f. The entire

true and 0 converts to false, so C++ will evaluate
(5 && 7) + (!6)
as follows. In the expression (5 && 7), the 5 and 7 convert to true; true && true
evaluates to
true, which C++ converts to 1. In the expression (!6) the 6 is converted to
true, so !(true) evaluates to false, which C++ converts to 0. Thus, the entire expression
evaluates to
1 + 0, which is 1. The final value is thus 1. C++ will convert the number 1 to
true, but the answer has little intuitive meaning as true; it is perhaps better to just say the
answer is
1. There is no need to become proficient at evaluating these nonsense expressions,
but doing a few will help you to understand why the compiler does not give you an error
message when you make the mistake of mixing numeric and Boolean operators in a single
expression.
2. The expression
2 < x < 3 is legal. However, it does not mean
(2 < x) && (x < 3)
as many would wish. It means (2 < x) < 3. Since (2 < x) is a Boolean expression, its
value is either
true or false and is thus converted to either 0 or 1, either of which is less
than
3. So, 2 < x < 3 is always true. The result is true regardless of the value of x.
3.
(x < –1 || (x > 2)
4. (x > 1 && (x < 3)
5. No. In the Boolean expression, (j > 0) is false (j was just assigned -1). The && uses
short-circuit evaluation, which does not evaluate the second expression if the truth value
can be determined from the first expression. The first expression is
false, so the second
does not matter.

else
cout << "OK";
You may want to add \n to the end of the above quoted strings, depending on the other
details of the program.
10. All nonzero integers are converted to
true; 0 is converted to false.
a. 0 is false
b. 1 is true
c. –1 is true
11. Start
Hello from the second if.
End
Start again
End again
12. large
13. small
14. medium
15. Both of the following are correct:
if (n < 0)
cout << n << " is less than zero.\n";
Answers to Self-Test Exercises 87
else if ((0 <= n) && (n <= 100))
cout << n << " is between 0 and 100 (inclusive).\n";
else if (n >100)
cout << n << " is larger than 100.\n";
and
if (n < 0)
cout << n << " is less than zero.\n";
else if (n <= 100)
cout << n << " is between 0 and 100 (inclusive).\n";

30. a. for (int i = 1; i <= 10; i++)
if (i < 5 && i != 2)
cout << ‘X’;
b. for (int i = 1; i <= 10; i = i + 3)
cout << ‘X’;
c. cout << ‘X’// necessary to keep output the same. Note
// also the change in initialization of n
for (long n = 200; n < 1000; n = n + 100)
cout << ‘X’;
31. The output is 1024 10. The second number is the base 2 log of the first number. (If the
first number is not a power of 2, then only an approximation to the base 2 log is produced.)
32. The output is
1024 1. The semicolon after the first line of the for loop is probably a pit-
fall error.
33. This is an infinite loop. Consider the update expression,
i = i * 2. It cannot change i
because its initial value is
0, so it leaves i at its initial value, 0. It gives no output because of
the semicolon after the first line of the
for loop.
34. a. A
for loop
b. and c. Both require a
while loop because the input list might be empty.
d. A
do-while loop can be used because at least one test will be performed.
35. This is an infinite loop. The first few lines of output are as follows:
10
13
16

today. Write a program to gauge the expected cost of an item in a specified number of
years. The program asks for the cost of the item, the number of years from now that the
item will be purchased, and the rate of inflation. The program then outputs the estimated
cost of the item after the specified period. Have the user enter the inflation rate as a per-
centage, such as 5.6 (percent). Your program should then convert the percentage to a frac-
tion, such as 0.056, and should use a loop to estimate the price adjusted for inflation.
(Hint: Use a loop.)
2. You have just purchased a stereo system that cost $1000 on the following credit plan: no
down payment, an interest rate of 18% per year (and hence 1.5% per month), and
monthly payments of $50. The monthly payment of $50 is used to pay the interest, and
whatever is left is used to pay part of the remaining debt. Hence, the first month you pay
1.5% of $1000 in interest. That is $15 in interest. The remaining $35 is deducted from
your debt, which leaves you with a debt of $965.00. The next month you pay interest of
1.5% of $965.00, which is $14.48. Hence, you can deduct $35.52 (which is $50–$14.48)
from the amount you owe.
Write a program that will tell you how many months it will take you to pay off the loan, as
well as the total amount of interest paid over the life of the loan. Use a loop to calculate the
amount of interest and the size of the debt after each month. (Your final program need not
output the monthly amount of interest paid and remaining debt, but you may want to
write a preliminary version of the program that does output these values.) Use a variable to
count the number of loop iterations and hence the number of months until the debt is
zero. You may want to use other variables as well. The last payment may be less than $50 if
the debt is small, but do not forget the interest. If you owe $50, then your monthly pay-
ment of $50 will not pay off your debt, although it will come close. One month’s interest
on $50 is only 75 cents.
For additional
online
Programming
Projects, click the
CodeMate icons


void
Functions 111

return
Statements in

void
Functions 112
Preconditions and Postconditions 113

main
Is a Function 115
Recursive Functions 116
3.3 SCOPE RULES 117
Local Variables 117
Procedural Abstraction 120
Global Constants and Global Variables 121
Blocks 124
Nested Scopes 124
Tip: Use Function Calls in Branching and Loop Statements 125
Variables Declared in a

for
Loop 125
CHAPTER SUMMARY 126
ANSWERS TO SELF-TEST EXERCISES 127
PROGRAMMING PROJECTS 130
this page intentionally blank)



, and

method

, which you may have heard before,
mean essentially the same thing as

function

. In C++ a function may return a
value (produce a value) or may perform some action without returning a
value, but whether the subpart returns a value or not, it is still called a func-
tion in C++. This chapter presents the basic details about C++ functions.
Before telling you how to write your own functions, we will first tell you how
to use some predefined C++ functions.

Predefined Functions

Do not reinvent the wheel.

Common saying

C++ comes with libraries of predefined functions that you can use in your
programs. There are two kinds of functions in C++: functions that return
(produce) a value and functions that do not return a value. Functions that do
not return a value are called

void


2

is equal to 9.) The function

sqrt

starts with a number, such as 9.0, and computes its
square root, in this case 3.0. The value the function starts out with is called its

argu-
ment

. The value it computes is called the

value returned.

Some functions may have
more than one argument, but no function has more than one value returned.
The syntax for using functions in your program is simple. To set a variable named

theRoot

equal to the square root of

9.0

, you can use the following assignment statement:

theRoot = sqrt(9.0);


bonus = sqrt(sales)/10;
sales

and

bonus

are variables that would normally be of type

double

. The function call

sqrt(sales)

is a single item, just as if it were enclosed in parentheses. Thus, the above
assignment statement is equivalent to

bonus = (sqrt(sales))/10;

You can use a function call wherever it is legal to use an expression of the type specified
for the value returned by the function.
Display 3.1 contains a complete program that uses the predefined function

sqrt

.
The program computes the size of the largest square doghouse that can be built for the
amount of money the user is willing to spend. The program asks the user for an
amount of money and then determines how many square feet of floor space can be pur-


include

directives. It does not matter in what order
you give these two

include

directives.

include

directives were discussed in Chapter 1.
Definitions for predefined functions normally place these functions in the

std

namespace and so also require the following

using

directive, as illustrated in Display 3.1:

using namespace std;
argument
value
returned
function
call or
function

1 //Computes the size of a doghouse that can be purchased
2 //given the user’s budget.
3 #include <iostream>
4 #include <cmath>
5 using namespace std;
6 int main( )
7 {
8 const double COST_PER_SQ_FT = 10.50;
9 double budget, area, lengthSide;
10 cout << "Enter the amount budgeted for your doghouse $";
11 cin >> budget;
12 area = budget/COST_PER_SQ_FT;
13 lengthSide = sqrt(area);
14 cout.setf(ios::fixed);
15 cout.setf(ios::showpoint);
16 cout.precision(2);
17 cout << "For a price of $" << budget << endl
18 << "I can build you a luxurious square doghouse\n"
19 << "that is " << lengthSide
20 << " feet on each side.\n";
21 return 0;
22 }
S
AMPLE
D
IALOGUE
Enter the amount budgeted for your doghouse $25.00
For a price of $25.00
I can build you a luxurious square doghouse
that is 1.54 feet on each side.


labs

; and if you want to produce the absolute value
of a number of type

double

, use fabs. To complicate things even more, abs and labs
are in the library with header file cstdlib, whereas fabs is in the library with header
file
cmath. fabs is an abbreviation for floating-point absolute value. Recall that numbers
with a fraction after the decimal point, such as numbers of type
double, are often called
floating-point numbers.
Another example of a predefined function is
pow, which is in the library with header
file
cmath. The function pow can be used to do exponentiation in C++. For example, if
you want to set a variable
result equal to
x
y
, you can use the following:
result = pow(x, y);
Hence, the following three lines of program code will output the number 9.0 to the
screen, because
(3.0)
2.0
is 9.0:

,. . .,
Argument_Last
E
XAMPLES
side = sqrt(area);
cout << "2.5 to the power 3.0 is "
<< pow(2.5, 3.0);
fabs
pow
96 Function Basics
Notice that the previous call to pow returns 9.0, not 9. The function pow always
returns a value of type
double, not of type int. Also notice that the function pow
requires two arguments. A function can have any number of arguments. Moreover,
every argument position has a specified type, and the argument used in a function call
should be of that type. In many cases, if you use an argument of the wrong type, some
automatic type conversion will be done for you by C++. However, the results may not
be what you intended. When you call a function, you should use arguments of the type
specified for that function. One exception to this caution is the automatic conversion
of arguments from type
int to type double. In many situations, including calls to the
Display 3.2 Some Predefined Functions
All these predefined functions require
using namespace std; as well as an include directive.
NAME DESCRIPTION TYPE OF
ARGUMENTS
TYPE OF
VALUE
RETURNED
EXAMPLE VALUE LIBRARY

fabs(7.5)
7.5
7.5
cmath
ceil
Ceiling
(round up)
double double ceil(3.2)
ceil(3.9)
4.0
4.0
cmath
floor
Floor
(round
down)
double double floor(3.2)
floor(3.9)
3.0
3.0
cmath
exit
End program
int void exit(1);
None
cstdlib
rand
Random
number
None

an action, a
void function invocation is a statement. The function call for a void func-
tion is written similar to a function call for a function that returns a value, except that it
is terminated with a semicolon and is used as a statement rather than as an expression.
Predefined
void functions are handled in the same way as predefined functions that
return a value. Thus, to use a predefined
void function, your program must have an
include directive that gives the name of the library that defines the function.
For example, the function
exit is defined in the library cstdlib, and so a program
that uses that function must contain the following at (or near) the start of the file:
#include <cstdlib>
using namespace std;
The following is a sample invocation (sample call) of the function exit:
exit(1);
void
F
UNCTIONS
A void function performs some action, but does not return a value. For a void function, a func-
tion call is a statement consisting of the function name followed by arguments enclosed in paren-
theses and then terminated with a semicolon. If there is more than one argument, the arguments
are separated by commas. For a
void function, a function invocation (function call) is a state-
ment that can be used like any other C++ statement.
S
YNTAX
Function_Name
(
Argument_List

invocation of the
exit function is a statement written as follows:
exit(
Integer_Value
);
When the exit function is invoked (that is, when the above statement is executed), the program
ends immediately. Any
Integer_Value
may be used, but by convention, 1 is used for a call to
exit that is caused by an error, and 0 is used in other cases.
The
exit function definition is in the library cstdlib and it places the exit function in the std
namespace. Therefore, any program that uses the
exit function must contain the following two
directives:
#include <cstdlib>
using namespace std;
Display 3.3 A Function Call for a Predefined void Function
1 #include <iostream>
2 #include <cstdlib>
3 using namespace std;
4 int main( )
5 {
6 cout << "Hello Out There!\n";
7 exit(1);
8 cout << "This statement is pointless,\n"
9 << "because it will never be executed.\n"
10 << "This is just a toy program to illustrate exit.\n";
11 return 0;
12 }

tions. Since you can think of the value returned as being a random number, you can
use a random number generator to simulate random events, such as the result of throw-
ing dice or flipping a coin. In addition to simulating games of chance, random number
generators can be used to simulate things that strictly speaking may not be random but
that appear to us to be random, such as the amount of time between the arrival of cars
at a toll booth.
sqrt(16.0) sqrt(16) pow(2.0, 3.0)
pow(2, 3) pow(2.0, 3) pow(1.1, 2)
abs(3) abs(-3) abs(0)
fabs(-3.0) fabs(-3.5) fabs(3.5)
ceil(5.1) ceil(5.8) floor(5.1)
floor(5.8) pow(3.0, 2)/2.0 pow(3.0, 2)/2
7/abs(-2) (7 + sqrt(4.0))/3.0 sqrt(pow(3, 2))
a. b. c.
d. e. f.
xy+
x
y 7+
area fudge+
time tide+
nobody

bb
2
4ac–+–
2a

xy–
100 Function Basics
The C++ library with header file <cstdlib> contains a random number function

ever, if you could return the computer to the state it was in when the sequence of calls
to
rand began, you would get the same sequence of “random numbers.” Numbers that
appear to be random but really are not, such as a sequence of numbers generated by
calls to
rand, are called pseudorandom numbers.
A sequence of pseudorandom numbers is usually determined by one number known
as the seed. If you start the random number generator with the same seed, over and
over, then each time it will produce the same (random-looking) sequence of numbers.
You can use the function
srand to set the seed for the function rand. The void function
srand takes one (positive) integer argument, which is the seed. For example, the follow-
ing will output two identical sequences of ten pseudorandom numbers:
int i;
srand(99);
for (i = 0; i < 10; i++)
cout << (rand( ) % 11) << endl;
srand(99);
for (i = 0; i < 10; i++)
cout << (rand( ) % 11) << endl;
rand
RAND_MAX
scaling
pseudorandom
number
seed
srand
Predefined Functions 101
There is nothing special about the number 99, other than the fact that we used the
same number for both calls to

P
SEUDORANDOM
N
UMBERS
The function rand takes no arguments and returns a pseudorandom integer in the range 0 to
RAND_MAX (inclusive). The void function srand takes one argument, which is the seed for the
random number generator
rand. The argument to srand is of type unsigned int, so the argu-
ment must be nonnegative. The functions
rand and srand, as well as the defined constant
RAND_MAX, are defined in the library cstdlib, so programs that use them must contain the
following directives:
#include <cstdlib>
using namespace std;
floating-
point
random
numbers
102 Function Basics
produced by another form of scaling. The following generates a pseudorandom floating-
point value between
0.0 and 1.0:
rand( )/static_cast<double>(RAND_MAX)
The type cast is made so that we get floating-point division rather than integer division.
Display 3.4 A Function Using a Random Number Generator
(part 1 of 2)
1 #include <iostream>
2 #include <cstdlib>
3 using namespace std;
4 int main( )

35 cout << "That's it from your 24-hour weather program.\n";
36 return 0;
37 }
Programmer-Defined Functions 103
Self-Test Exercises
5. Give an expression to produce a pseudorandom integer number in the range 5 to 10
(inclusive).
6. Write a complete program that asks the user for a seed and then outputs a list of ten ran-
dom numbers based on that seed. The numbers should be floating-point numbers in the
range
0.0 to 1.0 (inclusive).
Programmer-Defined Functions
A custom-tailored suit always fits better than one off the rack.
My uncle, the tailor
The previous section told you how to use predefined functions. This section tells you
how to define your own functions.

DEFINING FUNCTIONS THAT RETURN A VALUE
You can define your own functions, either in the same file as the main part of your pro-
gram or in a separate file so that the functions can be used by several different programs.
Display 3.4 A Function Using a Random Number Generator
(part 2 of 2)
S
AMPLE
D
IALOGUE
Welcome to your friendly weather program.
Enter today’s date as two integers for the month and the day:
2 14
Weather for today:

function. Thus, for the function
totalCost, the type of the value returned is double.
Next, the function declaration tells you the name of the function; in this case,
total-
Cost
. The function declaration tells you (and the compiler) everything you need to
know in order to write and use a call to the function. It tells you how many arguments
the function needs and what type the arguments should be; in this case, the function
totalCost takes two arguments, the first one of type int and the second one of type
double. The identifiers numberParameter and priceParameter are called formal param-
eters, or parameters for short. A formal parameter is used as a kind of blank, or place-
holder, to stand in for the argument. When you write a function declaration, you do
not know what the arguments will be, so you use the formal parameters in place of the
arguments. Names of formal parameters can be any valid identifiers. Notice that a
function declaration ends with a semicolon.
Although the function declaration tells you all you need to know to write a function
call, it does not tell you what value will be returned. The value returned is determined
by the function definition. In Display 3.3 the function definition is in lines 24 to 30 of
the program. A function definition describes how the function computes the value it
returns. A function definition consists of a function header followed by a function body.
The function header is written similar to the function declaration, except that the
header does not have a semicolon at the end. The value returned is determined by the
statements in the function body.
The function body follows the function header and completes the function defini-
tion. The function body consists of declarations and executable statements enclosed
within a pair of braces. Thus, the function body is just like the body of the
main part of
a program. When the function is called, the argument values are plugged in for the for-
mal parameters, and then the statements in the body are executed. The value returned
by the function is determined when the function executes a


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status