• No results found

A NSWERS TO S ELF -T EST E XERCISES

In document C++ Basics (Page 165-171)

Testing and Debugging Functions

A NSWERS TO S ELF -T EST E XERCISES

1. A by-value parameter is a local variable. When the function is invoked, the value of a call-by-value argument is computed and the corresponding call-call-by-value parameter (which is a local variable) is initialized to this value.

2. The function will work fine. That is the entire answer, but here is some additional informa-tion: The formal parameter inches is a call-by-value parameter and, as discussed in the text, is therefore a local variable. Thus, the value of the argument will not be changed.

3.10 20 30 1 2 3 1 20 3

4.Enter two integers: 5 10

In reverse order the numbers are: 5 5 5.void zeroBoth(int& n1, int& n2)

{

n1 = 0;

n2 = 0;

}

04_CH04.fm Page 166 Wednesday, August 13, 2003 12:49 PM

Answers to Self-Test Exercises 167

6.void addTax(double taxRate, double& cost) {

cost = cost + (taxRate/100.0)*cost;

}

The division by 100 is to convert a percentage to a fraction. For example, 10% is 10/100.0, or one-tenth of the cost.

7.par1Value in function call = 111 par2Ref in function call = 222 n1 after function call = 1 n2 after function call = 2

8. The one with one parameter would be used because the function call has only one parameter.

9. The first one would be used because it is an exact match, namely, two parameters of type double.

10. This cannot be done (at least not in any nice way). The natural ways to represent a square and a round pizza are the same. Each is naturally represented as one number, which is the radius for a round pizza and the length of a side for a square pizza. In either case the func-tion unitPrice would need to have one formal parameter of type double for the price and one formal parameter of type int for the size (either radius or side). Thus, the two function declarations would have the same number and types of formal parameters. (Spe-cifically, they would both have one formal parameter of type double and one formal parameter of type int.) Thus, the compiler would not be able to decide which definition to use. You can still defeat this evil pizza parlor’s strategy by defining two functions, but they will need to have different names.

11. The fundamental rule for testing functions is that every function should be tested in a pro-gram in which every other function in that propro-gram has already been fully tested and debugged. This is a good way to test a function because if you follow this rule, then when you find a bug, you will know which function contains the bug.

12. A driver program is a program written for the sole purpose of testing a function.

13. A stub is a simplified version of a function that is used in place of the function so that other functions can be tested.

14.//THIS IS JUST A STUB.

double rainProb(double pressure,

double humidity, double temp) {

return 0.25; //Not correct,

//but good enough for some testing.

}

Different

168 Parameters and Overloading

P

ROGRAMMING

P

ROJECTS

1. Write a program that converts from 24-hour notation to 12-hour notation. For example, it should convert 14:25 to 2:25 P.M. The input is given as two integers. There should be at least three functions: one for input, one to do the conversion, and one for output. Record the A.M./P.M. information as a value of type char, ’A’ for A.M. and ’P’ for P.M. Thus, the function for doing the conversions will have a call-by-reference formal parameter of type char to record whether it is A.M. or P.M. (The function will have other parameters as well.) Include a loop that lets the user repeat this computation for new input values again and again until the user says he or she wants to end the program.

2. The area of an arbitrary triangle can be computed using the formula

where a, b, and c are the lengths of the sides, and s is the semiperimeter.

Write a void function that uses five parameters: three value parameters that provide the lengths of the edges, and two reference parameters that compute the area and perimeter (not the semiperimeter). Make your function robust. Note that not all combinations of a, b, and c produce a triangle. Your function should produce correct results for legal data and reasonable results for illegal combinations.

3. Write a program that tells what coins to give out for any amount of change from 1 cent to 99 cents. For example, if the amount is 86 cents, the output would be something like the following:

86 cents can be given as

3 quarter(s) 1 dime(s) and 1 penny(pennies)

Use coin denominations of 25 cents (quarters), 10 cents (dimes), and 1 cent (pennies). Do not use nickel and half-dollar coins. Your program will use the following function (among others):

void computeCoin(int coinValue, int& number, int& amountLeft);

//Precondition: 0 < coinValue < 100; 0 <= amountLeft < 100.

//Postcondition: number has been set equal to the maximum number //of coins of denomination coinValue cents that can be obtained //from amountLeft cents. amountLeft has been decreased by the //value of the coins, that is, decreased by number*coinValue.

For example, suppose the value of the variable amountLeft is 86. Then, after the following call, the value of number will be 3 and the value of amountLeft will be 11 (because if you take three quarters from 86 cents, that leaves 11 cents):

computeCoins(25, number, amountLeft);

area = s s( –a)(sb)(sc)

s = (a+b+c)⁄2

04_CH04.fm Page 168 Wednesday, August 13, 2003 12:49 PM

Programming Projects 169

Include a loop that lets the user repeat this computation for new input values until the user says he or she wants to end the program. (Hint: Use integer division and the % operator to implement this function.)

4. Write a program that will read in a length in feet and inches and output the equivalent length in meters and centimeters. Use at least three functions: one for input, one or more for calculating, and one for output. Include a loop that lets the user repeat this computa-tion for new input values until the user says he or she wants to end the program. There are 0.3048 meters in a foot, 100 centimeters in a meter, and 12 inches in a foot.

5. Write a program like that of the previous exercise that converts from meters and centime-ters into feet and inches. Use functions for the subtasks.

6. (You should do the previous two programming projects before doing this one.) Write a program that combines the functions in the previous two programming projects. The pro-gram asks the user if he or she wants to convert from feet and inches to meters and centi-meters or from centi-meters and centicenti-meters to feet and inches. The program then performs the desired conversion. Have the user respond by typing the integer 1 for one type of conver-sion and 2 for the other conversion. The program reads the user’s answer and then executes an if-else statement. Each branch of the if-else statement will be a function call. The two functions called in the if-else statement will have function definitions that are very similar to the programs for the previous two programming projects. Thus, they will be fairly complicated function definitions that call other functions. Include a loop that lets the user repeat this computation for new input values until the user says he or she wants to end the program.

7. Write a program that will read in a weight in pounds and ounces and will output the equiv-alent weight in kilograms and grams. Use at least three functions: one for input, one or more for calculating, and one for output. Include a loop that lets the user repeat this com-putation for new input values until the user says he or she wants to end the program. There are 2.2046 pounds in a kilogram, 1000 grams in a kilogram, and 16 ounces in a pound.

8. Write a program like that of the previous exercise that converts from kilograms and grams into pounds and ounces. Use functions for the subtasks.

9. (You should do the previous two programming projects before doing this one.) Write a program that combines the functions of the previous two programming projects. The pro-gram asks the user if he or she wants to convert from pounds and ounces to kilopro-grams and grams or from kilograms and grams to pounds and ounces. The program then performs the desired conversion. Have the user respond by typing the integer 1 for one type of conver-sion and 2 for the other. The program reads the user’s answer and then executes an if-else statement. Each branch of the if-else statement will be a function call. The two functions called in the if-else statement will have function definitions that are very simi-lar to the programs for the previous two programming projects. Thus, they will be fairly complicated function definitions that call other functions in their function bodies. Include a loop that lets the user repeat this computation for new input values until the user says he or she wants to end the program.

170 Parameters and Overloading

10. (You should do Programming Projects 6 and 9 before doing this programming project.) Write a program that combines the functions of Programming Projects 6 and 9. The pro-gram asks the user if he or she wants to convert lengths or weights. If the user chooses lengths, then the program asks the user if he or she wants to convert from feet and inches to meters and centimeters or from meters and centimeters to feet and inches. If the user chooses weights, a similar question about pounds, ounces, kilograms, and grams is asked.

The program then performs the desired conversion. Have the user respond by typing the integer 1 for one type of conversion and 2 for the other. The program reads the user’s answer and then executes an if-else statement. Each branch of the if-else statement will be a function call. The two functions called in the if-else statement will have func-tion definifunc-tions that are very similar to the programs for Programming Projects 6 and 9.

Thus, these functions will be fairly complicated function definitions that call other func-tions; however, they will be very easy to write by adapting the programs you wrote for Programming Projects 6 and 9. Notice that your program will have if-else statements embedded inside of if-else statements, but only in an indirect way. The outer if-else statement will include two function calls, as its two branches. These two function calls will each in turn include an if-else statement, but you need not think about that. They are just function calls and the details are in a black box that you create when you define these functions. If you try to create a four-way branch, you are probably on the wrong track. You should only need to think about two-way branches (even though the entire program does ultimately branch into four cases). Include a loop that lets the user repeat this computation for new input values until the user says he or she wants to end the program.

04_CH04.fm Page 170 Wednesday, August 13, 2003 12:49 PM

For additional online Programming Projects, click the CodeMate icons below.

1.7

5 Arrays

5.1

INTRODUCTION TO ARRAYS 172 Declaring and Referencing Arrays 172 Tip: Use for Loops with Arrays 175

Pitfall: Array Indexes Always Start with Zero 175 Tip: Use a Defined Constant for the Size of an Array 175 Arrays in Memory 176

Pitfall: Array Index Out of Range 177 Initializing Arrays 178

5.2

ARRAYS IN FUNCTIONS 181

Indexed Variables as Function Arguments 181 Entire Arrays as Function Arguments 182 The const Parameter Modifier 185

Pitfall: Inconsistent Use of const Parameters 187 Functions That Return an Array 188

Example: Production Graph 188

5.3

PROGRAMMING WITH ARRAYS 194 Partially Filled Arrays 194

Tip: Do Not Skimp on Formal Parameters 194 Example: Searching an Array 197

Example: Sorting an Array 199

5.4

MULTIDIMENSIONAL ARRAYS 204 Multidimensional Array Basics 204 Multidimensional Array Parameters 205

Example: Two-Dimensional Grading Program 207 CHAPTER SUMMARY 211

ANSWERS TO SELF-TEST EXERCISES 212 PROGRAMMING PROJECTS 216

05_CH05.fm Page 171 Wednesday, August 13, 2003 12:51 PM

5 Arrays

It is a capital mistake to theorize before one has data.

Sir Arthur Conan Doyle, Scandal in Bohemia (Sherlock Holmes)

In document C++ Basics (Page 165-171)