CSCI 121: Chapter 4 Practice Problems

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Write a complete C++ program to compute and output the square root of PI; PI is approximately 3.14159. The const double PI is predefined in cmath. You are encouraged to use this predefined constant.

// Computes the square root of 3.14159 #include <iostream> #include <cmath> using namespace std; int main( ) { cout << "The square root of " << PI << " is " << sqrt(PI) << endl; return 0 }

Suppose you have two function definitions with the following function declarations: double theAnswer(double data1, double data2); double theAnswer(double time, int count); Which function definition would be used in the following function call and why would it be the one used? (x and y are of type double) 25. x = theAnswer(y, 6.0); 26. x = theAnswer(5, 6); 27. x = theAnswer(5, 6.0);

25. double theAnswer(double data1, double data2) because both arguments are of type double 26. double theAnswer(double time, int count); because the second number is of type int and the first would be automatically converted to type double. 27. double theAnswer(double data1, double data2); because the second argument is type double and the first would be converted to type double

Suppose a function named Function1 has a variable named sam declared within the definition of Funciton1, and a function named Function2 also has a variable named sam declared within the definition of Function2. Will the program compile (assuming everything else is correct)? If the program will compile, will it run? If it runs, will it generate an error message when run? If it runs and does not produce an error message when run, will it give the correct output?

Everything will be fine. the program will compile, run, will not generate an error message, and will give the correct output.

If you use a variable in a function definition, where should you declare the variable? In the function definition? In the main part of the program? Any place that is convenient?

If you use a variable in a function definition, you should declare the variable in the body of the function definition.

Carefully describe the process of program testing.

In order to increase your confidence in your program, you should test it on input values for which you know the correct answers. Perhaps you can calculate the answers by some other means, such as pencil and paper or hand calculator.

List the similarities and differences between use of a predefined (that is, library) function and a user-defined function.

Predefined (library) functions usually require that you #include a header file. For a programmer-defined function, the programmer puts the code for the function either into the file with the main part of the program or in another file to be compiled and linked to the main program.

Carefully describe the call-by-value parameter mechanism.

Suppose the function is defined with arguments, say param1 and param2. The function is then called with corresponding arguments arg1 and arg2. The values of the arguments are "plugged in" for the corresponding formal parameters, arg1 into param1, arg2 into param2. The formal parameters are then used in the function.

What is the purpose of the comment that accompanies a function declaration?

The comment explains what value the function returns and gives any other information that you need to know in order to use the function.

Looking at the program in Display 4.18. The main function contains the using directive: using namespace std; Why doesn't the method unitPrice contain this using directive?

The definition of unitPrice does not do any input or output so does not use the library iostream. In main we needed the using directive because cin and cout are defined in iostream and those definitions place cin and cout in the std namespace.

Write a function declaration and a function definition for a function that takes one argument of type double. The function returns the character value 'P' if its argument is positive and returns 'N' if its argument is zero or negative.

The function declaration is: char positiveTest(double number); //Returns 'P' if number is positive. //Returns 'N' if number is negative or zero. The function definition is: char positiveTest(double number) { if (number > 0) return 'P'; else return 'N'; }

Write a function declaration and function definition for a function called readFilter that has no parameters and that returns a value of type double. The function readFilter prompts the user for a value of type double and reads the value into a local variable. The function returns the value read provided this value is greater than or equal to zero and returns zero if the value read is negative.

The function declaration is: double readFilter(); //Reads a number from the keyboard. Returns the number read provided it is >= 0; otherwise returns zero. The function definition is: //uses iostream double readFilter() { using namespace std; double valueRead; cout << "Enter a number:\n"; cin >> valueRead; if (valueRead >= 0) return valueRead; else return 0.0; }

Write a function declaration and a function definition for a function that takes one argument of type in and one argument of type double, and that returns a value of type double that is the average of the two arguments.

The function declaration is: double ave(int n1, double n2); // Returns the average of n1 and n2. The function definition is: double ave(int n1, double n2); { return ((n1 + n2)/2.0); }

Write a function declaration and a function definition for a function that takes three arguments, all of type int, and that returns the sum of its three arguments.

The function declaration is: int sum(int n1, int n2, int n3); // Returns the sum of n1, n2, and n3. The function definition is: int sum(int n1, int n2, int n3) { return (n1 + n2 + n3); }

The following function is supposed to take as arguments a length expressed in feet and inches and return the total number of inches in that many feet and inches. For example, total_inches(1, 2) is supposed to return 14, because 1 foot and 2 inches is the same as 14 inches. Will the following function perform correctly? If not, why not? double total_inches(int feet, int inches) { inches = 12 * feet + inches; return inches; }

The function will work fine.

What is the principle of procedural abstraction as applied to function definitions?

The principle of procedural abstraction says that a function should be written so that it can be used like a black box. This means that the programmer who uses the function need not look at the body of the function definition to see how the function works. The function declaration and accompanying comment should be all the programmer needs to know in order to use the function.

This question has to do with the Programming Example "Revised Pizza-Buying Program." Suppose the evil pizza parlor that is always trying to fool customers introduces a square pizza. Can you overload the function unitPrice so that it can compute the price per square inch of a square pizza as well as the price per square inch of a round pizza? Why or why not?

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 diameter for a round pizza and the length of a side for a square pizza. In either case the function 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. 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 function, but they will need to have different names.

What does it mean when we say the programmer who uses a function should be able to treat the function like a black box?

When we say that the programmer who uses a function should be able to treat the function like a black box, we mean the programmer should not need to look at the body of the function definition to see how the function works. The function declaration and accompanying comment should be all the programmer needs to know in order to use the function.

What is the output produced by the following program? #include <iostream> using namespace std; char mystery(int firstPar, int secondPar); int main() { cout << mystery(10,9) << "ow\n"; return 0; } char mystery(int firstPar, int secondPar) { if (firstPar >= secondPar) return 'W'; else return 'H'; }

Wow

Consider two possible definitions for the function unitPrice. One is the definition given in Display 4.10. The other definition is the same except that the type cast static_cast<double>(2) is replaced with the constant 2.0; in other words, the lin radius = diameter/static_cast<double>(2); is replaced with the line radius = diameter/2.0; Are these two possible function definitions black-box equivalent?

Yes, the function would return the same value in either case, so the two definitions are black-box equivalent.

Write and compile short programs to test the following issues: a. Determine whether your compiler will allow the #include<iostream> anywhere on the line, or if the # needs to be flush with the the left margin b. Determine whether your compiler will allow space between the # and the include

a. //To determine whether the compiler will tolerate spaces before the # in the #include: #include <iostream> using namespace std; int main( ) { cout << "hello world" << endl; return 0; } b. //To determine if the compiler will allow spaces between the # and include in the #include: # include<iostream> using namespace std; //The rest of the program will be identical to part a.

Determine the value of each of the following arithmetic expressions: a. sqrt(16.0) b. pow(2,3) c. abs(3) d. fabs(-3.0) e. ceil(5.1) f. floor (5.8) g. 7/abs(-2) h. sqrt(16) i. pow(2.0, 3) j. abs(-3) k. fabs(-3.5) l. ceil(5.8) m. pow(3.0, 2)/2.0 n. (7 + sqrt(4.0))/3.0 o. pow(2.0, 3.0) p. pow (1.1, 2) q. abs(0) r. fabs(3.5) s. floor(5.1) t. pow(3.0, 2)/2 u. sqrt(pow(3,2))

a. 4.0 b. 8.0 c. 3 d. 3.0 e. 6.0 f. 5.0 g. 3 h. 4.0 i. 8.0 j. 3 k. 3.5 l. 6.0 m. 4.5 n. 3.0 o. 8.0 p. 1.21 q. 0 r. 3.5 s. 5.0 t. 4.5 u. 3.0

Convert each of the following mathematical expressions to a C++ arithmetic expression: a. sqrt(x+y) b. sqrt(time+tide)/nobody c. x^(y+7) d. quadratic formula e. sqrt(area + fudge) f. abs(x-y)

a. sqrt(x + y) b. sqrt(time + tide)/nobody c. pow(x, y + 7) d. (-b + sqrt(b * b - 4 * a * c))/(2 * a) e. sqrt(area + fudge) f. abs(x - y) OR labs(x - y) OR fabs(x - y)

Write a function definition for a function called even that takes one argument of type int and returns a bool value. The function returns true if its one argument is an even number; otherwise, it returns false.

bool even(int n) { return ((n % 2) == 0); }

Write a function definition for a function called inOrder that takes three arguments of type int. The function returns true if the three arguments are in ascending order; otherwise, it returns false. For example, inOrder(1, 2, 3) and inOrder(1, 2, 2) both return true, while inOrder(1, 3, 2) returns false.

bool inOrder(int n1, int n2, int n3) { return ((n1 <= n2) && (n2 <= n3)); }

Write a function definition for a function isDigit that takes one argument of type char and returns a bool value. The function returns true if the argument is a decimal digit; otherwise, it returns false.

bool isDigit(char ch) { return ('0' <= ch) && (ch <= '9') }

Write a function definition for a function isRootOf that takes two arguments of type int and returns a bool value. The function returns true if the first argument is the square root of the second; otherwise, it returns false.

bool isRootOf(int rootCandidate, int number) { return (number == rootCandidate * rootCandidate); }

Suppose you have two function definitions with the following function declarations: double score(double time, double distance); int score(double points); Which function definition would be used in the following function call and why would it be the one used? (x is of type double) finalScore = score(x)

int score(double points), because the function call has only on argument


Kaugnay na mga set ng pag-aaral

MRKT 347 International Business Ch. 10 Study Guide

View Set

Head, Neck, and neurological ATI

View Set

World War 2 Events/Turning Points/Themes

View Set

Chapter 13 - Sexuality and the Adult Years

View Set

Med Surg Unit 1 & 2 (Test 1) (Oncology Management and Hematologic Function)

View Set