Chapter 5: User-Defined Functions: Participation Activities

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

True or False: A function that changes the value of a global variable is sometimes said to have "side effects".

Answer: True Explanation: Unexpected side effects of a function can make program maintenance hard.

True or False: Using assert() is a preferred way to test a function.

Answer: True Explanation: assert() enables a concise test harness and simplifies spotting a failed test vector in the program's output.

True or False: A local variable is defined inside a function, while a global is defined outside any function.

Answer: True Explanation: globals should be used carefully, and not as a replacement for parameters.

Original parameters were num1, num2, and num3. Original code was: int sum = 0; sum = (num1 * num1) + (num2 * num2) + (num3 * num3); return sum; New parameters are num1, num2, num3, and num4. Find the error in the new code below: int sum = 0; sum = (num1 * num1) + (num2 * num2) + (num3 * num3) + (num3 * num4); return sum;

(num3 * num4)

Returning the incorrect variable from a function is a common error.

Answer: True Explanation: This type of error may be had to find, as sometimes the returned value might be correct.

Which correctly passes two integer arguments for the function call CalcVal(...)?

Answer: (99, 44 + 5) Explanation: Each argument evaluates to an integer.

Which correctly defines two integer parameters x and y for a function definition void CalcVal(...)?

Answer: (int x, int y) Explanation: Each parameter has a type and a name. The comma separate the two parameters.

Given a funtion definition: void CalcVal(int a, int b, int c) and given int variables i, j, and k, which are valid arguments in the call CalcVal(...)?

Answer: (k, i + j, 99) Explanation: There are three integer arguments, so k's value will be assigned to a, i + j to b, and 99 to c.

Given the PrintFace() function defined above and the following main() function: int main() { PrintFace(); PrintFace(); return 0; } How many function definitions of PrintFace() exist within main()?

Answer: 0 Explanation: The function definition would usually appear before main() in the program file.

True or False: A return address indicates the value returned by the function.

Answer: False Explanation: When the function completes, an instruction jumps back to where the caller left off at using the previously-stored return address.

True or False: Assigning a pass by value parameter in a function is discouraged due to potentially leading to a bug where a later line of code reads the parameter assuming the parameter still contains the original value.

Answer: True Explanation: The normal and intuitive use of a parameter is to hold an argument's value, not to also act as a local variable that is assigned.

Forgetting to return a value from a function is a common error.

Answer: True Explanation: The value returned from a function without a return statement is undefined.

Given: #include <iostream> using namespace std; /* Returns fee charged by ebay.com given the selling price of fixed-price books, movies, music, or video-games. Fee is $0.50 to list plus 13% of selling price up to $50.00, 5% of amount from $50.01 to $1000.00, and 2% for amount $1000.01 or more. Source: http://pages.ebay.com/help/sell/fees.html, 2012. Note: double variables are not normally used for dollars/cents due to the internal representation's precision, but are used here for simplicity. */ // Function determines eBay price given item selling price double EbayFee(double sellPrice) { const double BASE_LIST_FEE = 0.50; // Listing Fee const double PERC_50_OR_LESS = 0.13; // % $50 or less const double PERC_50_TO_1000 = 0.05; // % $50.01..$1000.00 const double PERC_1000_OR_MORE = 0.02; // % $1000.01 or more double feeTot = 0.0; // Resulting eBay fee feeTot = BASE_LIST_FEE; // Determine additional fee based on selling price if (sellPrice <= 50.00) { // $50.00 or lower feeTot = feeTot + (sellPrice * PERC_50_OR_LESS); } else if (sellPrice <= 1000.00) { // $50.01..$1000.00 feeTot = feeTot + (50 * PERC_50_OR_LESS ) + ((sellPrice - 50) * PERC_50_TO_1000); } else { // $1000.01 and higher feeTot = feeTot + (50 * PERC_50_OR_LESS) + ((1000 - 50) * PERC_50_TO_1000) + ((sellPrice - 1000) * PERC_1000_OR_MORE); } return feeTot; } int main() { double sellingPrice = 0.0; // User defined selling price // Prompt user for selling price, call eBay fee function cout << "Enter item selling price (Ex: 65.00): "; cin >> sellingPrice; cout << "eBay fee: $" << EbayFee(sellingPrice) << endl; return 0; } What does EvayFee() function return if its argument is 0.0 (show your answer in the form #.##)?

Answer: 0.50 Explanation: feeTot is first set to 0.50. Next, the first branch executes (i.e. sellPrice <= 50.00), which adds (0 * 0.13 = 0) to feeTot.

What will be printed for the following function call: PrintSum(1, 2);

Answer: 1 + 2 is 3 When PrintSum(1, 2) is called, 1 is assigned to the function's first parameter nm1, and 2 to num2.

Given the PrintFace() function defined above and the following main() function: int main() { PrintFace(); PrintFace(); return 0; } How many function calls to PrintFace() exist in main()?

Answer: 2 Explanation: The first call to PrinFace() will print a face. The second call will print a face again.

Given: #include <iostream> using namespace std; /* Returns fee charged by ebay.com given the selling price of fixed-price books, movies, music, or video-games. Fee is $0.50 to list plus 13% of selling price up to $50.00, 5% of amount from $50.01 to $1000.00, and 2% for amount $1000.01 or more. Source: http://pages.ebay.com/help/sell/fees.html, 2012. Note: double variables are not normally used for dollars/cents due to the internal representation's precision, but are used here for simplicity. */ // Function determines eBay price given item selling price double EbayFee(double sellPrice) { const double BASE_LIST_FEE = 0.50; // Listing Fee const double PERC_50_OR_LESS = 0.13; // % $50 or less const double PERC_50_TO_1000 = 0.05; // % $50.01..$1000.00 const double PERC_1000_OR_MORE = 0.02; // % $1000.01 or more double feeTot = 0.0; // Resulting eBay fee feeTot = BASE_LIST_FEE; // Determine additional fee based on selling price if (sellPrice <= 50.00) { // $50.00 or lower feeTot = feeTot + (sellPrice * PERC_50_OR_LESS); } else if (sellPrice <= 1000.00) { // $50.01..$1000.00 feeTot = feeTot + (50 * PERC_50_OR_LESS ) + ((sellPrice - 50) * PERC_50_TO_1000); } else { // $1000.01 and higher feeTot = feeTot + (50 * PERC_50_OR_LESS) + ((1000 - 50) * PERC_50_TO_1000) + ((sellPrice - 1000) * PERC_1000_OR_MORE); } return feeTot; } int main() { double sellingPrice = 0.0; // User defined selling price // Prompt user for selling price, call eBay fee function cout << "Enter item selling price (Ex: 65.00): "; cin >> sellingPrice; cout << "eBay fee: $" << EbayFee(sellingPrice) << endl; return 0; } For any call to EbayFee() function, how many assignment statements for the variable feeTot will execute? Do not count variable initialization as an assignment.

Answer: 2 Explanation: Two statements will execute. The first statement, feeTot = BASE_LIST_FEE; always executes. Then exactly one branch will be taken executing a feeTot = feeTot+ ...

Given the PrintFace() function defined above and the following main() function: int main() { PrintFace(); PrintFace(); return 0; } How many output statements exist in PrintFace()?

Answer: 3 Explanation: The PrintFace() definition has 3 output statements. The number of calls does not change that. When the program runs, those statements may execute, perhaps multiple times.

Given: #include <iostream> #include <cmath> using namespace std; // Function prompts user to enter postiive non-zero number int GetPositiveNumber() { int userNum = 0; while (userNum <= 0) { cout << "Enter a positive number (>0): " << endl; cin >> userNum; if (userNum <= 0) { cout << "Invalid number." << endl; } } return userNum; } // Function returns greatest common divisor of two inputs int FindGCD(int aVal, int bVal) { int numA = aVal; int numB = bVal; while (numA != numB) { // Euclid's algorithm if (numB > numA) { numB = numB - numA; } else { numA = numA - numB; } } return numA; } // Function returns least common multiple of two inputs int FindLCM(int aVal, int bVal) { int lcmVal = 0; lcmVal = abs(aVal * bVal) / FindGCD(aVal, bVal); return lcmVal; } int main() { int usrNumA = 0; int usrNumB = 0; int lcmResult = 0; cout << "Enter value for first input" << endl; usrNumA = GetPositiveNumber(); cout << endl << "Enter value for second input" << endl; usrNumB = GetPositiveNumber(); lcmResult = FindLCM(usrNumA, usrNumB); cout << endl << "Least common multiple of " << usrNumA << " and " << usrNumB << " is " << lcmResult << endl; return 0; } How many user-defined function calls exist in the program code?

Answer: 4 Explanation: main() calls GetPositiveNumber() twice, then calls FindLCM(), which itself calls FindGCD, giving a total of 4 function calls.

Assume a function void PrintNum(int userNum) simply prints the value of userNum without any space or new line. What will the following output? PrintNum(43); PrintNum(21);

Answer: 4321 Explanation: The first call prints 43. The second call prints 21 immediately after, so the entire output is 4321.

Given a function definition: void CalcVal(int a, int b, int c) what value is assigned to b during this function call: CalcVal(42, 55, 77);

Answer: 55 Explanation: That second argument's value will be assigned to the second parameter b.

Given the PrintFace() function defined above and the following main() function: int main() { PrintFace(); PrintFace(); return 0; } How many output statements would execute in total?

Answer: 6 Explanation: Each PrintFace() call causes the function to execute, and executes 3 output statements. There are two calls, so 2 * 3 = 6.

Given: double SquareRoot(double x) { ... } void PrintVal(double x) { ... } Is this a valid statement: y = SquareRoot(SquareRoot(16.0));

Answer: True Explanation: The inner SquareRoot(16.0) evaluates to 4.0. Then, the output SquareRoot(4.0) evaluates to 2.0, which is assigned to y.

True or False: A common reason for using functions is to create code that is easier to understand.

Answer: True Explanation: The intent of code may be clearer if cnosisting of a few calls to functions with meaningful names, rather than of tens or hundreds of statements.

Given: #include <iostream> using namespace std; /* Returns fee charged by ebay.com given the selling price of fixed-price books, movies, music, or video-games. Fee is $0.50 to list plus 13% of selling price up to $50.00, 5% of amount from $50.01 to $1000.00, and 2% for amount $1000.01 or more. Source: http://pages.ebay.com/help/sell/fees.html, 2012. Note: double variables are not normally used for dollars/cents due to the internal representation's precision, but are used here for simplicity. */ // Function determines eBay price given item selling price double EbayFee(double sellPrice) { const double BASE_LIST_FEE = 0.50; // Listing Fee const double PERC_50_OR_LESS = 0.13; // % $50 or less const double PERC_50_TO_1000 = 0.05; // % $50.01..$1000.00 const double PERC_1000_OR_MORE = 0.02; // % $1000.01 or more double feeTot = 0.0; // Resulting eBay fee feeTot = BASE_LIST_FEE; // Determine additional fee based on selling price if (sellPrice <= 50.00) { // $50.00 or lower feeTot = feeTot + (sellPrice * PERC_50_OR_LESS); } else if (sellPrice <= 1000.00) { // $50.01..$1000.00 feeTot = feeTot + (50 * PERC_50_OR_LESS ) + ((sellPrice - 50) * PERC_50_TO_1000); } else { // $1000.01 and higher feeTot = feeTot + (50 * PERC_50_OR_LESS) + ((1000 - 50) * PERC_50_TO_1000) + ((sellPrice - 1000) * PERC_1000_OR_MORE); } return feeTot; } int main() { double sellingPrice = 0.0; // User defined selling price // Prompt user for selling price, call eBay fee function cout << "Enter item selling price (Ex: 65.00): "; cin >> sellingPrice; cout << "eBay fee: $" << EbayFee(sellingPrice) << endl; return 0; } What does EbayFee() function return if its argument is 100.00 (show your answer in the form #.##)?

Answer: 9.50 Explanation: feeTot is first set to 0.50. Next, the second branch executes (i.e. sellPrice <= 100.00), which adds ((50 * 0.13) + ((100 - 50) * 0.05) = 6.5 + 2.5 = 9) to feeTot.

A benefit of functions is to increase redundant code.

Answer: False Explanation: A function can decrease redundant code so that the same group of statements does not have to be written in multiple places.

True or False: If a function's local variable has the same name as a function parameter, the name will refer to the local variable.

Answer: False Explanation: A function can't define two items with the same name. Th compiler will generate an error.

True or False: After a function returns, its local variables keep their values, which serve as their initial values the next time the function is called.

Answer: False Explanation: A function's local variables are discarded from memory upon a function's return; each new call creates new local variables in memory.

True or False: A test harness involves temporarily modifying an existing program to test a particular function within that program.

Answer: False Explanation: A test harness is typically a separate program whose purpose is to test a function. Modifying an existing program and then modifying it back could introduce bugs.

A key reason for creating functions to help main() run faster.

Answer: False Explanation: Actually, functions may cause slightly slower execution. But they have other, far more important advantages, like improved readability.

True or False: A local variable's scope extends from a function's opening brace to the function's closing brace.

Answer: False Explanation: Not from the opening brace, but rather from the variable's definition to the closing brace.

True or False: For a function with three integer inputs, about 3-5 test vectors is likely sufficient for testing purposes.

Answer: False Explanation: One might instead test dozens of normal cases, and perhaps ten or so border cases.

Given: double SquareRoot(double x) { ... } void PrintVal(double x) { ... } Is this a valid statement: y = PrintVal(9.0);

Answer: False Explanation: PrintVal() has void return type, so cannot be assigned to a variable.

Given: double SquareRoot(double x) { ... } void PrintVal(double x) { ... } Is this a valid statement: y = 1 + PrintVal(9.0);

Answer: False Explanation: PrintVal() has void return type, so cannot be used as such within an expression.

Avoiding redundancy means to avoid calling a function from multiple places in a program.

Answer: False Explanation: Redundancy refers to writing the same code in multiple places. We may want to write that code in a function, then call the function from multiple places in a program.

Given: double SquareRoot(double x) { ... } void PrintVal(double x) { ... } Is this a valid statement: y = SquareRoot();

Answer: False Explanation: SquareRoot requires one argument of type double.

Given: double SquareRoot(double x) { ... } void PrintVal(double x) { ... } Is this a valid statement: y = SquareRoot;

Answer: False Explanation: SquareRoot requires one argument of type double.

True or False: A good programmer takes the time to test all possible input values for a function.

Answer: False Explanation: Testing all possible input values is simply not practical except for the most trivial of functions. A function with just one integer parameter has over 4 billion possible input values.

Given: double SquareRoot(double x) { ... } void PrintVal(double x) { ... } Is this a valid statement: SquareRoot(49.0) = z;

Answer: False Explanation: The left side of an assignment statement must be a variable, not an expression.

True or False: A function declaration lists the contents of a function, while a function definition just specifies the function's interface.

Answer: False Explanation: The opposite: The declaration specifies the interface while the definition specifies the contents.

True or False: Unit testing means to modify function inputs in small steps known as units.

Answer: False Explanation: Unit refers to a part of a program, typically a function. Unit testing means to test just that part, separately from other program parts.

A key benefit of function stubs is faster running programs.

Answer: False Explanation: Using function stubs mainly helps a programmer capture correct high-level behavior before getting distracted by low-level details.

If a function's internal statements are revised, all function calls will have to be modified too.

Answer: False Explanation: Usually not. This is one of the advantages of function—the inner details are not relevant to the caller.

Given: #include <iostream> #include <cmath> using namespace std; // Function prompts user to enter postiive non-zero number int GetPositiveNumber() { int userNum = 0; while (userNum <= 0) { cout << "Enter a positive number (>0): " << endl; cin >> userNum; if (userNum <= 0) { cout << "Invalid number." << endl; } } return userNum; } // Function returns greatest common divisor of two inputs int FindGCD(int aVal, int bVal) { int numA = aVal; int numB = bVal; while (numA != numB) { // Euclid's algorithm if (numB > numA) { numB = numB - numA; } else { numA = numA - numB; } } return numA; } // Function returns least common multiple of two inputs int FindLCM(int aVal, int bVal) { int lcmVal = 0; lcmVal = abs(aVal * bVal) / FindGCD(aVal, bVal); return lcmVal; } int main() { int usrNumA = 0; int usrNumB = 0; int lcmResult = 0; cout << "Enter value for first input" << endl; usrNumA = GetPositiveNumber(); cout << endl << "Enter value for second input" << endl; usrNumB = GetPositiveNumber(); lcmResult = FindLCM(usrNumA, usrNumB); cout << endl << "Least common multiple of " << usrNumA << " and " << usrNumB << " is " << lcmResult << endl; return 0; } Other than main(), which user-defined function calls another user-defined function? Just write the function name.

Answer: FindLCM() Explanation: FindLCM() calls FindGCD().

What is the most appropriate function definition for this: Compute the area and diameter of a circle given the radius.

Answer: More than one function should be written. Explanation: One function should calculate area, the other diameter. Those items are not closely interrelated and are separately useful, too.

Given: void PrintSomething (int num1) { ... } Is return 0; a valid return statement?

Answer: No Explanation: Nothing should be returned. The proper statement is: return;

Given: int CalculateSomeValue(int num1, int num2) { ... } Is this an appropriate return statement: return;

Answer: No Explanation: The return should supply an integer because the function definition indicates an int return type.

Is this function correct for squaring an integer? int sqr(int a) { int t; t = a * a; }

Answer: No Explanation: The return statement is missing.

Is this function correct for squaring an integer? int sqr(int a) { int t; t = a * a; return a; }

Answer: No Explanation: The wrong value is returned.

Given: int CalculateSomeValue(int num1, int num2) { ... } Is this an appropriate return statement: return num1 num2;

Answer: No Explanation: num1 num 2 is not an expression. Also, two values cannot be returned.

Given: int CalculateSomeValue(int num1, int num2) { ... } Is this an appropriate return statement: return void;

Answer: No Explanation: void is not an integer.

Call a function named PrintAge, passing the value 21 as an argument.

Answer: PrintAge(21); Explanation: In contrast to a parameter, an argument is passed without a type indication. An argument is an expression like 21, myAge, myAge + 21, etc.

Write a function call using PrintSum() to print the sum of x and 400 (providing the arguments in that order). End with ;

Answer: PrintSum(x, 400); Explanation: If x is 99, then PrintSum(x, 400) will print: 99 + 400 = 499.

Given: double SquareRoot(double x) { ... } void PrintVal(double x) { ... } Is this a valid statement: SquareRoot(9.0);

Answer: True Explanation: The expression evaluates to 3.0. Nothing is done with that value. The statement is legal, but not useful.

True or False: Assigning a pass by value parameter can avoid having to define a local variable.

Answer: True Explanation: Avoiding having to define a local variable is not very important. Such avoidance is perhaps a "lazy" programming trick that should be avoided.

Copying-and-pasting code can lead to common errors if all necessary changes are not made to the pasted code.

Answer: True Explanation: Being aware of this common error will help to ensure you vigilantly modify any pasterd functions to implement the correct functionality.

True or False: For function, border cases might include 0, a very large negative number, and a very large positive number.

Answer: True Explanation: Border cases typically include large-magnitude values, and a-typical inputs like 0.

True or False: Assigning a pass by value parameter in a function is discouraged due to potentially confusing a program reader into believing the argument is being updated.

Answer: True Explanation: Eventually, somebody else may have to maintain a program. So, making the program code very clear is important.

Incremental development may involve more frequent compilation, but ultimatel lead to faster development of a program.

Answer: True Explanation: Frequent compilation leads to catching erors earlier before multiple errors begin to interact with one another in strange ways.

Modular development means to divide a program into separate modules that can be developed and tested separately and then integrated into a single program.

Answer: True Explanation: Modular development can yield programs that are correct and easier to maintain.

Given: double SquareRoot(double x) { ... } void PrintVal(double x) { ... } Is this a valid statement: y = 1.0 + SquareRoot(144.0);

Answer: True Explanation: SquareRoot(144.0) evaluates to 12.0. Then 1.0 + 12.0 is 13.0, which is assigned to y.

Given: double SquareRoot(double x) { ... } void PrintVal(double x) { ... } Is this a valid statement: y = SquareRoot(49.0);

Answer: True Explanation: SquareRoot(49.0) evaluates to 7.0, which is then assigned to y.

True or False: If a unction's local variable has the same name as a global variable, the name will refer to the local variable.

Answer: True Explanation: Such naming can confuse a reader. Best to avoid such naming if possible.

True or False: A function declaration enables calls to the function before the function definition.

Answer: True Explanation: The function definition may be long, sobeing able to put it somewhere else can help make programs more readable.

Given: double SquareRoot(double x) { ... } void PrintVal(double x) { ... } Is this a valid statement: PrintVal(9.0);

Answer: True Explanation: This is the normal usage of a function with void return type.

Given: int CalculateSomeValue(int num1, int num2) { ... } Is this an appropriate return statement: return 9;

Answer: Yes Explanation: The expression 9 evaluates to an integer, so is a valid return value for this function.

Given: int CalculateSomeValue(int num1, int num2) { ... } Is this an appropriate return statement: return (0);

Answer: Yes Explanation: The expression evaluates to 0, an integer. The parentheses aren't wrong, but are unnecessary.

Given: int CalculateSomeValue(int num1, int num2) { ... } Is this an appropriate return statement: return (num1 + num2) + 1;

Answer: Yes Explanation: The expression evaluates to an integer.

Given: int CalculateSomeValue(int num1, int num2) { ... } Is this an appropriate return statement: return 9 + 10;

Answer: Yes Explanation: The return expression evaluates o 19, which is an integer.

Given: int CalculateSomeValue(int num1, int num2) { ... } Is this an appropriate return statement: return num1;

Answer: Yes Explanation: num1 evaluates to an integer value.

Complete the function definition, creating pass by value or pass by reference parameters as appropriate. Convert userMeters into userFet and userInches (three parameters, in that order), types are doubles. void MetersToFeetInches( )

Answer: double userMeters, double& userFeet, double& userInches Explanation: Pass by reference enables the function to "return" the two interrelated values of feet and inches.

What is the most appropriate function definition for this: Convert inches into centimeters.

Answer: int InchToCM(int inches) ... Explanation: The function returns centimeters.

Complete the function beginning to page a parameter named userAge of type int. void PrintAge( )

Answer: int userAge Explanation: The parameter indicates te type followed by the parameter name

Is the following a valid function definition beginning? Type yes or no. void MyFct(int userNum + 5) { ... }

Answer: no Explanation: A parameter is like a variable definition. I cannot be an expression.

Find the error in the function's code: int ComputeEquation1(int num, int val, int k) { int sum = 0; sum = (num * val) + (k * val); return num; }

Answer: return num; Explanation: Should be return sum, not num. Better identifiers would help.

Find the error in the function's code: int ComputeSumOfSquares(int num1, int num2) { int sum = 0; sum = (num1 * num1) + (num2 * num2); return; }

Answer: return; Explanation: Should be: return sum;

What is the most appropriate function definition for this: Get a user's full name by prompting "Enter full name" and then automatically separating into first and last names.

Answer: void GetUserFullName(string& firstName, string& lastName) ... Explanation: The function likely will have a single prompt "Enter full name," then splits the text into first and last, returning both via the pass by reference parameters.

Given the PrintFace() function defined above and the following main() function: int main() { PrintFace(); PrintFace(); return 0; } Is main() itself a function definition? Answer yes or no.

Answer: yes Explanation: A program must define a main() function, which is automatically called first when a program executes.


Set pelajaran terkait

Pedi Module 3 Children with special needs

View Set

Ch. 4/5 Diffusion, Osmosis and Enzymes

View Set

Reading- I Know Why the Caged Bird Sings and Travels with Charley Study Guide

View Set

exercise physiology - stretch-shortening cycle

View Set

Unit 6 Test: SYSTEM DESIGN AND DECISION MAKING

View Set

Vocabulary Workshop Second Course - Lesson 2

View Set

Ch 1: Introduction and Institutions

View Set