100% satisfaction guarantee Immediately available after payment Both online and in PDF No strings attached 4.6 TrustPilot
logo-home
Exam (elaborations)

Absolute C++ 5th Edition by Walter Savitch - Test Bank

Rating
-
Sold
-
Pages
372
Grade
A
Uploaded on
20-09-2023
Written in
2022/2023

Chapter 3 – Function Basics --Test Questions These test questions are true-false, fill in the blank, multiple choice, and free form questions that may require code. The multiple choice questions may have more than one correct answer. You are required to mark and comment on correct answers.. Mark all of the correct answers for full credit. The true false questions require an explanation in addition to the true/false response, and, if false, also require a correction. True False: An explanation is required. 1. Every programmer must know all the details of what that programmer's team mates are doing in their projects to do the work assigned. Why? Answer:. False Explanation: Only the client programmer needs to know the use to which a function is put. Only the author of the function needs to know the internals. The only thing these two share is the contract or specification of the function. 2. Procedural abstraction involves information hiding in that only the 'contract' between the programmer using the function (the client) and author of a function is known to either. Answer: True. Explanation: Under procedural abstraction, the author (or programmer) of a given function should know about how the application programmer (or the client) will use the function is IN the ‘contract.’ The contract is what the function is to do, and the conditions set on the parameters to guarantee that the function can do IT. The author should not need not know how the function is to be used by the client programmer. The client programmer should know only only needs to know what the function does, the requirements on the parameters, but not how the function carries out the task. This way each can do his job independently of the other. 3. Code after a return or a call to the exit function is executed will not be executed. Answer: True. Control returns to the caller if return is executed out of a called Test Bank for Savitch Absolute C++ 5e Page 2 function, and returns to the operating system if return is executed out of main. If exit is executed anywhere, the program is terminated and control is returned to the operating system. 4. A sequence of calls to the library function rand() generates mathematically correct random number sequences. Answer: False. Explanation: The sequence is called pseudorandom because it appears to be random. The results are good enough to obtain usable answers with computer simulation. 5. It is legal to replace the prototype double totalCost(int numberParam, double priceParam); with the more terse, alternate form double totalCost(int, double); Answer: True. Explanation: The alternate form applies only to function declarations. You will see this form in manuals. It is possible to omit variable names that will not be used in function definitions, but the text does not do this. 6. In C++ Boolean value are represented only with the int values 0 for false and 1 for true. Answer: False. Explanation: In C++ the bool type is a real type, with values true and false, but 0 is interpreted as true and 0 as false, and true and false will be converted to 1 and 0 respectively. 7. Extensive use of global variables is a satisfactory replacement for the difficulties of parameter passing with functions. Answer: False. Explanation: Global variable use ties functions together so tightly that it is impossible ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 3 to understand any one function’s behavior apart from the whole of the program. This complexity makes understanding a program very difficult. 8. A variable declared outside any function is said to be a local variable. Answer: False. Explanation: This is a global variable. 9. A variable declared within a function block is said to be local to the function. Answer: True Explanation: Such a variable is said to be local to the function or to have the function as its scope, and is also known as a local variable if the scope is clear from the context. 10. Consider two blocks, one within another. If an identifier is declared as a variable in the inmost of these two blocks, one can access this variable from the outer block. Answer: False: Explanation: The scope of a local variable extends from the definition to the end of the block in which the variable is defined. This excludes the outer block. 11. Consider two blocks, one within another. C++ prohibits an identifier to be declared as a variable in each of these blocks. Answer: False Explanation: Without the inner variable, the scope of the outer variable would be the entire outer block, including the inner block. The variable with the inner block for its scope shadows the outer variable’s scope, making a hole in the scope of the outer variable. 12. Calling something a black box is a figure of speech that conveys the idea that you cannot see inside. You know its behavior and interface but not its implementation. Answer: True Explanation: If a function is well designed, a client programmer can use it without knowing the internals. All the programmer needs to know is that if the preconditions ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 4 on the arguments are met, all he or she has to do is to name the function and enter the arguments. The black box will take care of everything else. Free Form Questions: 1. Convert the following mathematics expressions to C++ expressions. Use the declarations provided. Indicate the appropriate header file for any library function used. Be sure you initialize any variables whose values you are using to reasonable values for the library functions you are using. int x, y; //declaration for a) and b) a) y = x3 b) y <= |x| double x, y, z, area; //declaration for c) through e). c) z = x1.6 d) z = area area x2 y e) p = x2  y Answer: Values used for initialization are arbitrary except for obvious things, such as the sign of the argument for the sqrt must be nonnegative and the sign of the first argument (the base for the exponential) for the pow function cannot be negative unless the second argument is an integer. a) //no include file necessary for this expression int y, x = 39; // any value for x y = x x x; //alternate solution using pow function. #include <cmath> using namespace std; y = pow(x, 3); b) #include <cstdlib> ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 5 using namespace std; int y; intx = -23; // any value for x y = abs(x); // or #include <math.h> double y, x = -79.8; // any value for y y = fabs(x); c) #include <cmath> using namespace std; double z, x = 2.6; z = pow(x, 1.6); d) #include <cmath> using namespace std; double z, area = 144; // here area must not be // negative z = area sqrt(area); // the pow function can be used for this: z = pow (area, 1.5); e) // no includes are necessary here double p, x = 3, y = -4; //any values for x, y except x = y p = (x * x + y) / (x * x - y); //specifications can be interpreted to allow //int variables as well 2. Of what value are comments that accompany a function declaration? Answer: These comments describe the requirements for correct behavior of the function and the value returned by the function and any other effects of the function for a person who does might not have access to or the desire to read the source code. ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 6 3. Write code that declares x, y, and z as double variables. Then write code that causes z to be assigned the result of x divided by y, rounded as indicated below. Be sure to #include the header file that declares the library functions you use. a) round up b) round down c) round to the nearest integer. Does your code round an exact half up or down? say 2.5? Answer: The header is required for each answer. #include <math> using namespace std; double x, y, z; We mentioned what the code does for 2.5. Suppose x is 5.0 and y is 2.0 so we get a quotient of 2.5 a) //round up z = ceil(x/y); for above values we get 3.0 b) // round down z = floor(x/y); for above values we get 2.0 c) //round nearest integer z = floor (x/y + 0.5); For above values of x and y we get 3 4. Each of the following lines of code purport to round the results of the division of doubles to the nearest integer value (but still of type double). All are correct C+ + code but some do not round correctly. Tell which rounds down, up, or to the nearest integer value, or is not reasonable ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 7 Assume that math.h has been included, and that all variables have appropriate values. double x, y, z; a) z = ceil(x/y); b) z = ceil(x/y-0.5); c) z = floor(x/y-0.5); d) z = floor(x/y+0.5); e) z = floor(x/y); Answer: a) rounds up -- to the next integer greater than or equal to x/y b) OK rounds to the integer nearest to x/y, exact 1/2 values round down c) not reasonable. x/y with value 1.25 gives 0 result. d) OK rounds to the integer nearest to x/y, exact 1/2 values round up e) rounds down to the next integer less than or equal to x/y 5. Declare (give a prototype for) a function named average_grade. This function returns a double and has four double arguments, test1, test2, test3, test4. The return value should be the average, or arithmetic mean of the four arguments. Be sure to include a "prototype comment" that tells briefly what the function does. Answer: //returns arithmetic mean of the arguments test1 - test4 double average_grade (double test1, double test2, double test3, double test4); 6. Define a function named average_grade. This function returns a double and has four double arguments, test1, test2, test3, test4. The return value should be the average, or arithmetic mean of the four arguments. Be sure to include a comment that tells briefly what the function does. Answer: // returns arithmetic mean of the arguments test1 - test4 double average_grade (double test1-, double test2, ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 8 double test3, double test4) { double average; average = (test1 + test2 + test3 + test4) / 4; return average; } This slightly more terse definition is sufficient: //returns arithmetic mean of the arguments test1 - test4 double average_grade (double test1, double test2, double test3, double test4) { return (test1 + test2 + test3 + test4) / 4; } 7. Give an outline for the general form of a programmer defined function. Answer: return_type funct_name (parameter_list) { //function body - compute return_value here return return_value; } Here parameter_list is a comma separated list of entries of the type argument_type argument_name. There could be multiple returns inside a branch. 8. In your own words discuss similarities and differences between a function and a small program. Answer: A function definition is like a small program. Differences are that a program uses input, say cin, for input, or an fstream object, whereas a function uses parameters for inputs. Similarities are many. A program uses cout for output to the screen. A ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 9 function can use cout to output to the screen. The function can return a value to the caller using a return statement. The program can, in fact, do this too, but such values can only be success codes. The function and the program each have bodies of code that call other functions and do computation to produce the values to satisfy specified. Each has local variables that are declared within the body. Finally, each can use global constants and variables (which are declared outside any function.) 9. Given the function declaration (prototype), does the compiler complain or compile if you call this using the following line? If the compiler complains, what is the complaint? //if score >= min_to_pass, returns 'P' for passing, //else returns 'F' for failing. char grade (int score, int min_to_pass); int main() { double fscore; char fgrade; int need_to_pass; //omitted code to get values for variables //fscore and need fgrade = grade(fscore, need); return 0; } Answer: The compiler complains about using a double for a parameter for a function calling for an int parameter. The reason is the C++ strong type checking. There is a possible loss of information when a double is sent to any kind of integer (char, int, long) parameter, or assigned to an integer. Warning messages from the Gnu g++ compiler are: ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 10 Line 14: warning: float or double used for argument 1 double grade(int, int); 10. What is the error in the following code? Why is this wrong? int f(int x) { int x; // code for function body } Answer: The declaration of the variable x in the function body will be flagged by the compiler as a multiple declaration of the variable Such an attempt at (re)declaring a parameter violates the C++ rule that all identifiers be declared exactly once, prior to use. The g++ compiler gives the following (somewhat cryptic) error messages. (The -fsyntax-only option is to cause checking the programs syntax, but not generate any other files in the event that there are no errors. Most compilers have a similar option.) g++ -fsyntax-only P P: In function `int f(int)': P: declaration of `x' shadows a parameter Compilation exited abnormally with code 1 at Mon Jul 10 07:10:07 11. Procedural abstraction requires the author of a function and the client (user) of that function to know and not to know certain things. Remark on who needs to know and who need not know each of the following items a) the requirements on the parameter values, b) exactly what the return value is to be, c) the implementation details, and d) the details of how the function is used by the client. Answer a) Both author and client must know the requirements on the parameter values b) Both client and author must know what the return value is to be, ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 11 c) Only the author needs to know the implementation details. d) Only the client needs to know the details of the use to which the function is put. 12. Here is a complete function that purports to return one of the roots of a quadratic given suitable parameters. It looks good, but fails to compile. Why? //returns one of the roots of the quadratic equation //a*x*x + b*x + c = 0 a!= 0 double root1 (double a, double b, double c) { return (-b + sqrt(b*b-4*a*c))/(2*a); } Answer: The function sqrt, called in the body of the function root1, has no declaration (or prototype) given. The rest of the code is correct. The following preprocessor directive is needed prior to the definition of the function root to get a declaration of sqrt. #include <math.h> Some systems will create a declaration of an un-type-checked function, to allow the compiler to find other errors. The user is warned, but linking usually fails in this event. 13. Write a function definition 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. Answer: bool even(int n) { return ((n % 2) == 0); } ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 12 14. Write a function definition for a isDigit function 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. Answer: bool isDigit(char ch) { return (‘0’ <= ch) && (ch <= ‘9’); } No if-else is needed, just evaluate the Boolean expression and return it. 15. Write a function definition for a function called inOrder that takes three arguments of type int. The function returns true if the arguments are in increasing order left to right; otherwise inOrder returns false. For example, inOrder(1, 2, 3) returns true, whereas inOrder(1,3,2) returns false. Answer: bool inOrder(int n1, int n2, int n3) { return ((n1 <= n2) && n2 <= n3)); } 16. Write a prototype and prototype comments for the sqrt library function. Answer: //precondition: argument >= 0 //postcondition: return_value * return_value == argument double sqrt( double parm); Multiple Choice There may be more than one correct answer. You must give all correct answers for full credit. An explanation is required. 1. A C++ predefined functions a) are usually provided in libraries b) make C++ harder than necessary. ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 13 c) must #include the proper header file d) are usually provided with the C++ compiler Answer: a) c) and d) Explanation: “predefined” and “library” are synonymous. Libraries are supplied by compiler vendors. 2. The sqrt function a) is provided in the <cmath> library header. b) returns the square of the argument c) returns the square root of the argument d) the argument type is int e) the return type is double. Answer: a) c) e). Explanation: d) the argument type for sqrt is double. b) is a “foil”. 3. A C++ predefined function a) argument is the value the predefined function starts with b) may be called any number of times in a program. c) computed value is the return value d) call is an expression that has the type specified as the return type of the function and can be used anywhere any other expression of that type could be used. e) #include is all that is ever necessary to provide access. Answer: a) b) c) d) Explanation: e) sometimes we need to explictily link to a library that the system does not search. 4. A call to a C++ function is a) The name of the function followed by empty parentheses. b) The name of the function followed by any number of arguments, regardless of the number of parameters in the definition. c) The name of the function followed by a number of arguments not greater than the number of parameters in the definition. ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 14 d) The name of the function followed by exactly the number of arguments as there are parameters in the definition. e) The name of the function only. Answer: d) Explanation: a) is correct only when the function has no parameters. b) only works for certain advanced function calls using the “varargs” facility that is not treated in the text. c) only works with default arguments which we have not yet studied. 5. A void function a) performs some action and returns a value b) performs some action but does not return a value c) is a statement d) call is written much like a call to a value returning function but is terminated with a semicolon. e) A void function may have a return statement but is not required to have one. Answer: b) c) d) e) Explanation: a) is wrong because a void function does not return a value. 6. What do the calls to exit(...) do? When exit(0) and exit(1) are called, what receives these arguments and what is done with them? a) The exit( ) function stops the program. The argument is discarded. b) The exit( ) function is obsolete. There is no longer any such function in the C++ libraries. c) The exit( ) function stops the program. The argument is passed to the operating system which uses it for an error code. d) The exit( ) function temporarily stops the program, and sends the argument to the operating system which uses it for an error code. The operating system restarts the program after fixing the error. e) The exit( ) function allows the systems programmer to escape when the power supply catches fire. Answer: c) ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 15 Explanation: The other answers are foils, with nothing to recommend them except that they might sound good to some students who have not adequately prepared. 7. Which of the following are not names of a C++ library function: a) abs b) sqrt c) random d) floor e) labs Answer: c) random is not a library function. Explanation: The closest library function name to random is rand which returns pseudorandom numbers or perhaps srand, which seeds the rand random number generator. 8. A void function can have >>”void” is wrong font. a) no arguments b) as many arguments as the programmer wishes c) no more than 3 arguments d) exactly one argument Answer: b) Explanation: The other answers are foils. The only correct answer is b), as many as the programmer wishes. 9. Which of the following code fragments gives a random double value between 2 and 5 inclusive? You can assume that the random number seed has been set and any needed definitions and initializations have been made. a) 3.0*rand() + 2 b) 3.0*(RAND_MAX-rand())/RAND_MAX + 2 c) ((RAND_MAX-rand())/static_cast<double>(RAND_MAX))*3 + 2 d) (RAND_MAX-rand())/static_cast<double>(RAND_MAX)*5 -2 e) rand()/static_cast<double>(RAND_MAX)*2 + 3 ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 16 Answer: Only d) gives consistently correct, useful answers. Explanation: Part a) The library function rand() returns an int, not a double, so this is not correct. Part b) is syntactically correct but rand() returns an int between 0 and RAND_MAX. On one compiler available to this writer RAND_MAX is 2,147,483,647 (the value of the largest possible int value, MAX_INT). In 3.0*(RAND_MAX-rand()) the subtraction is done then the multiplication. Integer overflow is assured on this system before the computation is complete. On another compiler, RAND_MAX is 32,767, so b) would work there. This solution is to be avoided. Part c): Divide and multiply associate left to right, so the expression (RAND_MAX-rand())/static_cast<double>(RAND_MAX) gives a double between 0.0 and 1.0. Multiplying by 3 scales this to 0.0 to 3.0, adding 2 gives 2.0 to 5.0 as required, without overflow. Parts d) and e) are wrong: d) gives a random number between 2.0 and 7.0. e) gives a random double between 3.0 and 5.0. 10. , A definition of a variable outside any function is called a a) local function definition b) global variable definition c) global function header d) global function definition e) local variable definition Answer: b) 11. Concerning return statements that functions can have: a) Value returning functions can have the statement return computed_value; b) void functions can have the statement return void; c) void functions must have a return; statement, with no argument. ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 17 d) void functions may terminate using a return; statement without an argument, or they may have no return statement at all, terminating by falling off the end of the function block. Answer: a) d) are correct Explanation: b) is a syntax error., c) is too coercive (corrected in Part d)). 12. Where can you not declare a variable in a C++ program? a) Within the parameter list of a function definition b) Within the block of a void function. c) Within the argument list of a function call d) Within a block nested within another block e) Within the block of a value returning function. Answer: c) Explanation: All except c) allow variable declarations. a) Variables defined in a parameter list would be parameters for the function, b) d) and e) would define local variables. 13. Which of the following statements about the definition and declaration of functions is not correct? a) Function declaration is exactly the same as function prototype. b) Function definition is exactly the same as function prototype. c) A function header is exactly the same as function prototype except for the semicolon. d) A function definition is a function header followed by the function block. e) A function header syntax is the following: return_type function_name parenthesized_parameter_list Answer: b) is incorrect. 14. A semicolon does not (usually) go after these with the exception of >>”with the exception of” seems to make no sense here a) while(condition) b) if(condition) ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 18 c) a function header to make it a function declaration d) int main( ) e) an expression to make it a statement Answer: c) and e) Explanation: a) could have a semicolon if the loop’s work is done with side effects in the condition. b) could have a semicolon if the programmer wants an empty statement for whatever reason. A semicolon after d) would be a syntax error. 15. In the function round of Display 3.6, which of these explains what happens in the body of the function? We reproduce the one line from the function body here: return static_cast<int>(floor(number+0.5)); a) This is overkill, it would be sufficient to use the floor function alone. b) Adding 0.5 to number pushes the range up so floor can produce the correct rounding. c) The static_cast<int> is used because floor returns a double. If the double value were returned, there would be at least a warning of a double to int conversion in returning the value. d) This is wrong. The argument for the floor function should be number-0.5. Answer: b) and c) are correct. Explanation: Numbers between floor(number)+0.5 and floor(number)+1 should round to floor(number)+1. The expression number+0.5 pushes numbers in the range floor(number) and floor(number)+0.5 up so floor will produce the correct rounded number. It pushes numbers between floor(number) and floor(number)+0.5 to floor(number)+0.5 up but leaves them so that floor will produce the correct rounded value, namely floor(number). 16. Given the function definition, which of the following are correct? int func(int n, double d) { int j = n; ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 19 double sum = 0; while( j >= 0) { sum += d; -j; } return sum; } With arguments 7and 2.0 a) returns 7*2 b) returns 7+2 c) returns 7! d) There is a syntax error in the program so it won’t run. e) It compiles but computes none of these. Answer: e). Explanation. The loop will not terminate, since the operator on j is a unary -, not the decrement operator --. (It appears to be unsuccessfully trying to compute n*d.) 17. Correct statements of similarities and differences between calling user defined functions and library functions are: a) Similarity: A call to either requires the function name followed by parenthesized comma separated list of arguments that match the prototype in number and type. b) Difference: Library functions require inclusion of header files for declarations but user defined functions do not require any declaration before use. c) Similarity: Either library or user defined functions may be value returning or void functions. d) Difference: Library functions all provide a return value, user functions must be void functions. ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 20 e) Difference Library function declarations (sometimes definitions) come from #include <header> statements. User functions require either explicit prototypes prior to use or a #include “user_header.h” for the prototypes Answer: Similarities are a) c) e) Explanation: b) and d) are foils that sound reasonable to the poorly prepared student, but are wrong. 18. Suppose the function from Display 3.7 has the return statement removed. Which of the statements below regarding this change are correct? Why? void iceCream(int number, double totalWeight) { if(number == 0) { cout << “cannot divide among zero customers.n”; return; } portion = totalWeight/number; cout << “Each one receives “ << portion << “ ounces of ice cream.” <<endl; } a) The code will not compile. b) The code will compile and run. The output will be unchanged. c) The code will compile. For a zero number of customers the code would produce a divide by zero run-time error. d) The program will compile and run correctly for 1 or more customers. The error for zero number of customers could be repaired by placing an else after the block belonging to the if. Answers: c) and d) are correct. Explanation: a) and b) are foils for the unwary. 19. Here is a small program. Which of the statements about the variables is correct? ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 21 #include <iostream> const double NUM = 2.9345358; double num = 3; double numTimes(int x); int main( ) { using namespace std; int value; cout << “Enter a value, I’ll multiply it by “ << NUM << endl; cin >> value; cout << “You entered “ << value << “ NUM times this is “ << numTimes(value) << endl; return 0; } double numTimes(int x) { double d; d = NUM * x; return d; } a) NUM is a global variable. b) num is a global constant. c) value is local variable in the main function d) d is a local variable in the numTimes function. Answer: c) and d) are correct. Explanation: Answers a) and b) are reversed: NUM is a global constant, and num is a global variable. ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e 20. Here is a small program. Which of the statements about this code is correct? #include <iostream> const double NUM = 2.9345358; double num = 3; double numTimes(int x); int main( ) { using namespace std; int value; cout << “Enter a value, I’ll multiply it by “ << NUM << endl; cin >> value; Page 22 cout << “You entered “ << value << “ NUM times this is “ << numTimes(value) << endl; return 0; } double numTimes(int x) { double d; d = NUM * x; return d; } a) The variable x is a parameter in function numTimes b) The variable value is an argument in a call to numTimes. c) The line double numTimes(int x); is a function definition. d) The line return d; in the function numTimes is necessary. e) The lines of code are a function declaration: double numTimes(int x) ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 23 { . . .} Answer: a) b) and d) are correct. Explanation: c) is a function declaration or prototype not a definition. e) is a definition. It is also a declaration, as definitions are also declarations, but the lines of code do not constitute a declaration. 21. Consider the following pair of functions. You are to assume that the ellipses (. . .) contain correct code sufficient that it with the code you can see will compile apart from the two variables named sam in the two functions. . ... void func1( ) { int sam; .. . } void func2( ) { int sam; .. . } int main( ) { func1(); func2(); .. . } a) This code will not compile because of the multiply defined variable sam. In the explanation give the compiler message you get on compiling. b) This code will compile just fine. c) This code will compile but will give a runtime error due to the multiply defined variable sam. In the explanation give the error message you get when this is run. ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 24 d) This code compiles and runs without any error messages. Explain why in the explanations. Answer: b) and d) are correct answers. The program will give correct results (providing all the rest of the code is correct.) Explanation: The two variables named sam are local to the several functions func1 and func2. They do not interfere with each other because they are in disjoint scopes. 22. What does it mean when we say a programmer using a function should be able to treat the function like a black box? a) This is meaningless. One must know how a function does its job to effectively use it. b) One must be able to rely on the description of the preconditions (requirements for use of the function) and the postconditions (promise of behavior to use the function). c) If one codes an application that uses a function with a knowledge of the internal mechanism of that function, then when the function’s maintainer changes its internal mechanism, the application programmer could be faced with changing the application code extensively. d) The most efficient programs are the ones that each function is designed to maximally use the internal behavior of every other function to speed up the code. Answer: b) and c) are the correct answers. Explanation: a) and c) are foils, explicit non-sense. Code that is written to exploit the internals of other functions is strongly coupled, and is nearly impossible to maintain. It may be fast, but there will be no way to replace one algorithm with another and retain well behaved code. 23. Assume this code fragment is embedded in an otherwise correct and complete program. What should be the output from this code segment? { for( int i = 0; i < 10; i++) { .. . ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 25 } cout << i << endl; } a) 10 b)9 c)0 d) The variable i is undefined in this scope, so this should not compile Answer: d) Explanation: The question is what the output should be, so the correct answer is d). The actual answer depends on what the compiler writer did. On several of my compilers I get 10. Behavior pre ISO C++ is that the variable i is defined in the outer scope shown here. 24. What is the difference between executing the return 0; statement and its rough equivalent, a call to the exit(0); function, or the difference between return 1; and exit(1);? a) These are very nearly equivalent anywhere they are encountered. b) These are very different if encountered in a function other than main();.The exit function terminates the program, returning control to the operating system, whereas return only terminates the function, returning control to the calling function. c) These are very nearly equivalent when executed in the main function. In main, these both terminate main and send a success code to the operating system, returning control to the operating system. d) Both these return control to the free store manager by way of the exception controller, sending the argument as an error code. Answer: b) and c) are correct answers. Explanation: a) is an obvious foil, d) is foil for the unwary test taker. 25. We studied the rand() and srand(int) library functions. The function rand() returns pseudorandom numbers. What does pseudorandom mean? What is srand for? ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 26 a) Repeated calls to the rand() function returns a string of numbers that are mostly different but they aren’t random in any sense. b) Pseudorandom numbers are things that resemble numbers but aren’t numbers. c) In scientific use the word pseudo means resembling. A pseudorandom number sequence resemble random number sequence, but are not strictly random. d) The function srand(arg) is a helper function for rand(). It must be called with the same argument, just before rand(), every time rand() is called. e) The function srand(arg) is the seeding function for rand(). Each call to s srand(arg) with a different argument enables a sequence of calls to rand() to generate a different sequence of pseudorandom numbers. Answer: c) and e) are correct answers. Explanation: a) is a little bit flaky, but in my opinion it is wrong. b) is clearly wrong. Following d) will result in a sequence of all the same number. 26. Given the following include directive (to get the declaration for the pow function from the math library): #include <math.h> Now make these declarations: double base = 2, exponent = 3, power = 4; Which of the following are correct invocations for the pow function? If any of the following is correct, give the value returned or assigned, and if apparently incorrect, explain. a) power = pow(base, exponent); b) pow(power, base, exponent); c) pow(base, exponent) = power; d) base = pow(exponent, power); Answers: a) value is 8. d) is correct, in spite of variable names. Explanation: b) incorrect, too many arguments for the pow function. ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 27 c) incorrect, attempts to assign to power to pow(base, exponent) which is not an l-value, that is, it is not possible to assign a value to this object. d) is correct. base is assigned the value of 3 to the power 4, 81. Correctness does not depend on variable names. However, these are strange names for the arguments for the pow function. There is very likely an intent error. Chapter 5 –Arrays– Test Questions These test questions are true-false, fill in the blank, multiple choice, and free form questions that may require code. The multiple choice questions may have more than one correct answer. You are required to mark and comment on correct answers.. Mark all of the correct answers for full credit. The true false questions require an explanation in addition to the true/false response, and, if false, also require a correction. True False: An explanation is required. 1. If we want to find the median of 100 scores, we need 100 separate variables to hold the data.. Answer: False Explanation: We can (much more easily) use an array of 100 of the type of the scores to find the median. 2. An array behaves like a list of variables each of which is of the same type and for which there is a uniform, convenient naming convention that can be declared in a single line of code. In the explanation, give an example of declaration and access. Answer: True. Explanation: For example, an array of 400 double values is declared double array[400]; Access for read or write is array[index], where 0<=index<400. 3. With arrays, indices start at any number the programmer chooses to indicate in the definition. Answer: False Explanation: Index values start at 0, not any other number, and run to one less than the declared size. Test Bank for Savitch Absolute C++ 5e Page 2 4. The programmer should always use a defined constant in an array declaration. Answer: True Explanation: The reason is flexibility. A program with an array with declared size of 5 only works with a maximum of 5 of whatever the array holds. If things change so that we need to process 17 of these things, we are faced with the difficult and error prone task of finding all places in the program that 5 is used as an array size, including situations where someone has done arithmetic with the 5 and some other number. Better to use a defined constant from the start. 5. When using an array, it is perfectly legal to access indexed variables with index values less than 0 or greater than or equal to the declared size of the array. Answer: False Explanation: These index values are out of range, or simply illegal. The compiler cannot catch this. Unless you access protected memory doing this, the C++ runtime system will not catch this mistake either. The programmer has the obligation of detecting illegal index values or assuring there will be none. 6. To call a function with an array parameter, write the array argument as the array name followed by empty square brackets, as in f(a[], 7); (The first argument is an array a, the second is the size.) Answer: False Explanation: The correct syntax is to put the naked array name in the argument slot for the array parameter. If this were the function declaration, void f(int x[],int size); the call would look like f(array_name, array_size); 7. Consider the array declaration, int x[20];. There is no memory allocated for x[20]. ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Answer: True Explanation: There is memory allocated for x[0] through x[19] but not for x[20]: 8. Arrays in C++ may have several different types stored in them. Answer: False Page 3 Explanation: The array must be declared using the name of the type that will be stored in them. Nothing else can be stored in that array. An attempt to store something else will result in an attempt by C++ to coerce the other type to the base type, but that is as far as you can go in putting another type into a C++ array. 9. Given the two C++ array declarations: int a[10], b[10]; You can successfully compute one array, say a, then assign b to a: a = b; Answer: False Explanation: You cannot assign arrays in C++. Some compilers allow this, but the Standard says this is illegal, and most compilers do not allow it. To do this you need to write a loop or otherwise copy individual indexed variables. 10. In the sequential search algorithm, items are examined alternately, odd then evens, in order to find whether the target value is in the array (and if the target is present, to the index of the target.) Answer: False. Explanation: The sequential search algorithm performs just as the name suggests: The elements are searched in sequential order, until the target is found (success) or the end of the array is found (failure). 11. In a sorting an array, the items in the array are rearranged so that for all j and k, if j < k, then array[j]<=array[k] ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 4 Answer: True Explanation: This is sorting into increasing order. This ignores sorting into decreasing order. Care should be taken not to compare elements with index values out of the range 0 to declared_size-1 12. In the definition, double d[10] = {0.0}; only d[0] is initialized to zero, the rest are uninitialized, just like x in the definition double x; Answer: False Explanation: The ISO C++ Standard requires that a Standard compliant compiler with an initializer list initialize the excess array elements to a zero value appropriate to the base array type. Most compilers comply. 13. If you need an array with more than one index, you can use a multidimensional array, which is actually an array of arrays. In the explanation, declare an array of doubles with 2 rows and 5 columns. Answer: True Explanation: Perhaps the easiest way to see this is to think of a two dimensional array as an array of lines on a page. The requested declarations is double array[2][5]; The first index is the row, or line number, and the second index is the column position within that row. 14. Indexed variables for an array are stored wherever the computer finds memory for the first indexed variable, then the next one is stored next to the first if there is space, and someplace else if not. Answer: False Explanation: Indexed variables of an array are stored contiguously, or next to each other. 15. C++ arrays check for out-of-range index values. ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 5 Answer: False. Explanation: C++ array access is directly to memory through addresses, and is designed to be as efficient as possible. The C++ Standard does not require a mechanism to detect out-of-range index values. Finally, no version of C++ this writer is aware of provides this feature. 16. A for-loop is a convenient way to step through an array. Answer: True Explanation: The for-loop provides convenient places for definition and initialization, testing, and updating a loop control variable. This variable is convenient to use as an array index in stepping through the array, as: for(int i = 0; i < declared_size; i++) cout << array[i} << " "; cout << endl; Free Form Questions: 1. Distinguish the use of the square brackets [] in a definition of an array and their use for access to some indexed variable of the array. Answer: In the definition of an array, for example, int array[10]; the [] are used to define the array, the number between the brackets specifies the declared size, that is, it specifies how many indexed variables are being defined. This could be any number. In the access to an indexed variable, for example, array[5] = 14; the number between the brackets specifies which of the indexed variables is being accessed. This must be between 0 and one less than the declared size of the array. Technically, the [] are called the subscripting operator. ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 6 2. Describe the difference in the meaning of the 5 in int x[5]; and the meaning of the 4 in x[4]. What are the meanings of the int, the [5] and the [4]? Answer: The statement, int x[5];, is a declaration, where 5 is the declared size, that is, the number of array elements. The int is the base type of the array. The expression x[4] is an access to the array indexed variable defined by the previous statement. The access is to the element having index 4, which is the 5th (and last) array element. 3. Give the syntax of an array declaration. Mention the base type and declared size. Answer: Array definition syntax is Base_type Array_name[Declared_size]; where base_type is the type of the indexed variables and declared_size is the number of indexed variables, namely array_name[0] through array_name[declared_size–1]. 4. In the array declaration double score[5]; identify the following: a) The array name b) The base type c) The declared size of the array d) The smallest and largest index values this array can have. e) Give one of the indexed variables (a.k.a. elements) of this array. Answer: a) The array name is score. b) The base type is double. c) The declared size is 5. d) The smallest index is 0, and the largest array index is 4. (as in all arrays) e) score[2] is one of the indexed variables. 5. Write a C++ code fragment that is assumed to be embedded in an otherwise complete and correct program. You are to assume the user has been prompted (so you don’t have to) for (exactly) 20 values of type int to be read from the keyboard, You are to use this input to fill an array. Do not write a full program, just the code fragment to do this. Do give declarations of the array and any variables you use. ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Answer: int i, a[20]; for(i=0; I <20; I++) cin >> a[i]; 6. Consider the declaration double a[10] = {1.2, 2.1, 3.3, 3.5, 4.5, 7.9, 5.4, Page 7 8.7, 9.9, 1.0}; Write a function named out_of_order that will test this array for the condition a[0] <= a[1] <= a[2] <= ... The function returns a -1 if the elements are not out of order, otherwise it returns the index of the first element that is out of order. Explain what you do to avoid out of bounds array access. Answer: int out_of_order(double array[], int size) { for(int i=0; i < size-1; i++) if (array[i] > array[i+1]) return i+1; return -1; } Explanation: The upper limit for index i is size-1 because we fetch a[i+1] for each i in the range of the loop. Otherwise we would fetch and compare a[size], causing erroneous results. (We don’t know what is in that location.) 7. Consider the following function definition: void tripler(int& n) { n = 3*n; } Given this definition, which of the following are acceptable function calls? int a[3] = {3,4,5}, number = 2; ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 8 a) tripler(a[2]); b) tripler(a[3]); c) tripler(a[number]); d) tripler(a); e) tripler(number); Answer: a), c) and d) are acceptable. Answer a) c) and e) (NOT d) Explanation is OK Explanation: b) has an illegal index. d) passes the array itself, but the parameter is a call-by-reference to an int, not an array of anything. 8. Consider the following function definition: void tripler(int& n) { n = 3*n; } Given these definitions what (if anything) is wrong with the following? int b[5] = {3,4,5,6,7}; for (int j = 1; j <= 5; j++) tripler(b[j]); a) Nothing is wrong with either bit of code. b) There are not enough initializers for the array. c) There is an illegal index in the loop. d) There are too many initializers in for the array. e) The call to the function requires different syntax. Answer: d) is the error. c) is also an error unless you use j < 5 rather than j <= 5 Explanation: There is nothing wrong with the array declaration and initialization. However, the loop has both an illegal index (5) and very likely an intent error. The loop runs 1 through 5 instead of the C++ idiom 0 through size-1. ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 9 9. Explain the error in the following code. You may give the warning message, or error message, your compiler might give for the following error, or you may describe the error. However you present the error, you must explain clearly what is wrong. #include <iostream> //Test question void show_array(int ar[], int size) { using namespace std; for(int i = 0; i < size; i++) cout << ar[i] << " "; cout << endl; } int main() { const int a[6] = {2, 4, 2, 3, 5}; show_array(a, 6); //... } Answer: void show_array(int ar[], int size) { //. . . } //^^^^ should be const to use a as an //argument. show_array(a, 6);//warning: pointer to const given for //argument 1 of 'void show_array(int*, int)' ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 10 The error message means that the compiler thinks the argument could be changed by the function, and considers this a violation of the programmer's promise not to change the array when the array was declared const. 10. Here is a list of 8 numbers. Use the selection sort algorithm to sort this list. Fill in this table with each iteration of the loop in the selection sort algorithm. Mark the place from which you are looking for the 'next smallest element'. In this display, the upper numbers are the indices, the lower numbers are in the corresponding positions. Use the several rows provided to show the sequence of steps. |------|------|------|------|------|------|------|- 8 6 10 2 16 4 18 14 |------|------|------|------|------|------|------|- |------|------|------|------|------|------|------|- |------|------|------|------|------|------|------|- |------|------|------|------|------|------|------|- |------|------|------|------|------|------|------|- |------|------|------|------|------|------|------|- ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 11 |------|------|------|------|------|------|------|- Answer: Exercise the Selection Sort Algorithm: X = start of terminal segment X------|------|------|------|------|------|------|- 8 6 10 2 16 4 18 14 ^ smallest in the segment swap with #0 move start of segment to index #1 |------X------|------|------|------|------|------|- 2 6 10 8 16 4 18 14 ^ smallest in the segment swap with #1 move start of segment to index #2 |------|------X------|------|------|------|------|---- 2 4 10 8 16 6 18 14 ^ smallest in the segment swap with #2 move start of segment to index #3 |------|-------|-------X------|-------|-----|-------|-- 2 4 6 8 16 10 18 14 ^ smallest in the segment swap with #3 move start of segment to index #4 ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 12 |------|-------|-------|-------X-------|------|-----|- 2 4 6 8 16 10 18 14 ^ smallest in the segment swap with # 4 move segment to index #5 |------|-------|-------|-------|-------X------|------|- 2 4 6 8 10 16 18 14 ^ smallest in the segment swap with # 5 move seg to index #6 -------|-------|-------|------|------|------X------|- 2 4 6 8 10 14 18 16 ^ smallest in the segment swap with #6 move seg to index #7 |------|-------|-------|------|------|------|------X-- 2 4 6 8 10 12 14 18 ^ smallest in the segment swap with #7 move seg to index #8, end of algorithm 11. Write the selection sort algorithm for an array of int in C++. You are to assume that there are predefined functions swapValues and indexOfSmallest, that is do not write these functions. However, you must write declarations with pre and post conditions for these functions. Answer: void swapValues(int & v1, int& v2); >>>Attach & to first int for consistency //precondition: args have been initialized //postcondition: v1post = v2pre, v2post = v1pre. ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 13 int indexOfSmallest(const int a[], int start, int numberUsed); //Precondition: startIndex is a legal index for array a // args are initialized. //Postcondition: index value such that a[i] is the //smallest of values in the array. void sort(int a[], int numberUsed) { int indexOfNextSmallest; for(int index=0; index < numberUsed-1; index++) {// place next smallest in a[index] indexOfNextSmallest = indexOfSmallest(a, index, numberUsed); swapValues(a[index], a[indexOfNextSmallest]); //Assert:[0]<=a[1]<=...<=a[index] are the smallest //of the original array elements. The rest of the //elements are at index values beyond index. } } Insert const before .any of the following array parameters that can be changed 12. to const. void output(double a[], int size); //Pre: a[0] through a[size-1] have values set. //Post: a[0] through a[size-1] have been displayed on the screen. ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 14 void dropOdd(int a[], int size); //Pre: a[0] through a[size-1] have values set. //Post: All odd numbers in a[0] through a[size-1] have //been changed to 0. Answer: void output(const double a[], int size); Explanation: Only the output function can have its array parameter changed to const: It does nothing for the client to make a value parameter const, and this can annoy the programmer. (She cannot assign the parameter as is sometimes needed.) The dropOdd function postcondition asserts that dropOdd will change its array argument, so we cannot make that array const. 13. What is the output of the following code? #include<iostream> int main() { using namespace std; double a[3] = {1.1, 3.3, 2.2}; cout << a[0] << " " << a[1] << " " a[1] = a[2]; cout << a[0] << " " << a[1] << " " Answer: The output is: 1.1 3.3 2.2 1.1 2.2 2.2 << a[2] << endl; << a[2] << endl; } Explanation: The value stored at the index 1 position is changed to the value from the index 2 position. The output reflects the contents original array and the changed array. 14. What is the problem with this code? ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 15 int .array[5]; >>Delete the dot for (int index = 1; index <=5; index++) array[index] = index /2; Answer: The array element array[5] does not exist, yet we are assigning a value to it. 15. Suppose we want an array to satisfy the condition, a[0] <= a[1] <= a[2] <= ... And suppose this code is written to implement a test of this condition #include <iostream> using namespace std; int main() { double array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // assume the array is filled somehow. for(int i=0; i < 10; i++) if (array[i] > array[i+1]) cout << "Array elements " << i << " and " << i + 1 << " are out of order.n"; } When this is run, we sometimes get the following puzzling output: Array elements 9 and 10 are out of order. Even more puzzling, sometimes we don’t get this output. Why? Answer: There is an index out of range. When index i has value 9, i + 1 is 10, so a[i+1], which is the same thing as a[10] causes an illegal access. The loop should stop with one fewer iterations. To correct this code, replace the for loop header with for(int i=0; i < 9; i++) ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 16 16. Assume you have a swap routine in place for doubles. Write a routine calls swap that reverses the entries in an array of doubles. Use this function declaration. void reverse( double a, int size); Carry out your reversal in place, do not make a local copy of the array Answer: The answer is in bold face embedded in a complete test program. #include <iostream> const int SIZE = 10; void swap(double& lhs, double& rhs) { double tmp = lhs; lhs = rhs; rhs = tmp; } void reverse( double a[], int size) { using namespace std; for (int i = 0; i < (size - 1)/2; i++) swap(a[i], a[size - i - 1]); } int main() { using namespace std; double foo[SIZE] = {0,1,2,3,4,5,6,7}; for (int i = 0; i < SIZE; i++) ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 17 cout << foo[i] << " "; cout << endl; reverse(foo, SIZE); for (int i = 0; i < SIZE; i++) cout << foo[i] << " "; cout << endl; } Explanation: Note the (size - 1)/2 in the for loop test. If this is size-1, the routine reverses the array twice, undoing the reverse. Multiple Choice There may be more than one correct answer. You must give all correct answers for full credit. An explanation is required. 1. In a) An integer type b) Non-negative c) Positive d) Less than or equal to the declared size of the array e) None of these is correct Answer: a) and b) are correct Explanation: c) excludes 0, a possible index value. d) includes the declared size, not allowed. e) is wrong as there are some correct answers. 2. Given the array declaration, int a[20]; The first element is written as: a) a[1] b) a[0] c) a C++ array indices, that is subscript values, must be ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 18 d) a[20] e) a[19] Answer: b) Explanation: a) and d) are wrong. Array elements at index values 1 and 19 clearly are not first, the element at 0 comes before either. c) is the address of the first element, it is not the first element. d) there is no element 20 . 3. Given the array declaration, int a[20]; The last (legal) element is written as: a) a[2] b) a[0] c) a d) a[20] e) a[19] Answer: e) the element at 19 (declared_size –1) is the last element. Explanation: a) b) and d) are wrong. Array elements at index 0 and 2 clearly are not last, these come before element at 19. c) a, the name of the array is the address of the first element, it is not an element. d) there is no element 20 . 4. Are the following array initializations correct? If not, why not? a)int x[4] = {8, 7, 6, 5, 4}; b) int x[] = {8, 7, 6, 5, 4}; c) int x[4] = {8, d) const int SIZE int x[SIZE]; e) const int SIZE int x[SIZE-4]; 7, 6}; =4; =4; Answer: b) c) and d) are correct. Explanation: In the correct answer c) the last array item, x[3] is initialized to 0 by default. The incorrect items: Part a) has too many initializers, part e) attempts to declare an array of (illegal) size 0.(Array indices range from 0 to declared_size–1. What could this mean if declared_size is 0?) ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 19 5. Which of the following are correct? Why are the others incorrect? When a function having an array formal parameter is called, the formal array parameter ... a) names a copy of the array argument. b) refers to exactly the same array as the calling program c) is passed the address of the argument, and the function needs further information about the array size to safely use an array parameter d) refers to the array using a name that is always different from the calling program's argument. Answer: c) is correct. Explanation: The rest are wrong. Answer a) suggests passing of arrays is call–by- value,. (It is not.) Answer b) suggests that the size of an array parameter is known to the function. (It is not.). Answer d) suggests that we cannot use the same identifier in the formal parameter and the argument. (Of course we can.) Suppose you have the following array declaration in a program. int yourArray[5]; Further suppose that in the implementation of C++ you are using an int that requires 4 bytes. i) When your program runs, how much memory is required for this array? ii) Suppose further that your array starts at memory location decimal 100. What will be the address of yourArray[3]? iii)If you wrote to the (illegal) index 7 position in yourArray to what address would this clobber? a) i) The array takes 5 bytes, ii) yourArray[3] will be an int located at Address 103. iii) writing to yourArray[7] will clobber an int starting at location 107. b) i) The array takes 10 bytes, ii) yourArray[3] will be an int located at Address 106. iii) writing to yourArray[7] will clobber an int starting at location 114 6. ©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. Test Bank for Savitch Absolute C++ 5e Page 20 c) i) The array takes 20 bytes, ii) yourArray[3] will be an int located at Address 112 iii) writing to yourArray[7] will clobber an int starting at location 128 d) The purpose of a high level language is to insulate the programmer from these details. It isn’t possible to know this without probing the source to the operating system and the compiler, or extensive debugging. Answer: c) is correct. Explanation a) would be correct for a 1 byte int, b) would be correct for a 2 byte int (older MS DOS and MS Windows systems.) d) is an answer appropriate to a language that does not provide low level access (e.g. Java.) 7. What is the output of the following code (assuming it is embedded in a correct and complete program)? char letter[5] = {'o', 'k', 'c', 'e', 'g'}; for(int i = 4; i >= 0; i-- ) cout << letter[i]; cout << endl; Choices: a) okceg b) gecko c) ecko followed by a character from an out of bounds access. d) kceg followed by a character from an out of bou

Show more Read less
Institution
Course











Whoops! We can’t load your doc right now. Try again or contact support.

Written for

Institution
Study
Course

Document information

Uploaded on
September 20, 2023
Number of pages
372
Written in
2022/2023
Type
Exam (elaborations)
Contains
Questions & answers

Subjects

Content preview

,Chapter 1 - Test Questions
These test questions are fill in the blank, multiple choice, and true-false. The multiple
choice questions may have more than one correct answer. There is one matching
question. Mark all of the correct answers for full credit.
True False questions require an explanation in addition to the true/false response, and, if
false, also require a correction.

True False:

Comment required.

1. OOP is an acronym that means Object Oriented Programming.
Answer: True.
Explanation: OOP is currently popular and is a powerful programming technique for a
large class of problems.
2. C++ not only supports OOP but also supports other programming styles.
Answer: True.
Explanation: C++ supports OOP and traditional procedure oriented programming.
3. The namespace facility is a tool used that assists in the study of genealogy.
Answer: False.
Explanation: The namespace facility helps prevent the libraries from “preempting all the
good names,” and allows us to use names we want whether the library has used them.
4. In C++ the variables Alpha, ALPHA and AlphA are the same identifier.
Answer: False.
Explanation: C++ is case sensitive, these are different identifiers.
5. In C++ the compiler will infer the type intended for a variable from the context in
which the variable occurs.
Answer: False.
Explanation: C++ requires every identifier to be declared prior to use. The type is
specified in the declaration.
6. A C++ declaration introduces only an identifier's spelling and specifies its type.
Answer: True.
Explanation: A declaration introduces the spelling and type, whereas a definition is a

,Test Bank for Savitch Absolute C++ 5e Page 2


declaration that also allocates memory.
7. A C++ declaration is a definition that also allocates storage for an identifier's value
(or function's body etc.).
Answer: True.
Explanation: A declaration introduces the spelling and type, whereas a definition is a
declaration that also allocates memory.
8. The range of values for an int variable is from about 0 to +2 billion.
Answer: False:
Explanation: The correct range is about –2 Billion to +2 Billion.
9. The names x, y, and z are satisfactory variable names for the lengths of the legs and
hypotenuse of a triangle.
Answer: False.
Explanation: Names should communicate to the human reader the meaning of the value.
These identifiers do not communicate the meaning of their values..
10. In C++ you can assign an expression of type int to a variable of type double with
no problem.
Answer: True.
Explanation: Assignment from an integer type to a floating point type can lose
information and should be avoided. Some compilers will warn, others may give an error
message, but you should avoid this.
11. In C++ you can assign an expression of type double to a variable of type int with
no problem.
Answer: False.
Explanation: In general assigning a floating point value to an integer variable mostly
loses information. A warning message (or an error message) is issued by C++ compilers.
12. To put a character into a cstring constant that causes the output to continue on the
next line, insert the escape sequence \t into the string constant.
Answer: False.
Explanation: \t is the tab escape sequence. Use \n instead.
13. If we execute this code in an otherwise correct and complete program:



©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

, Test Bank for Savitch Absolute C++ 5e Page 3

n = 1;
n = (n++) + (n++);
the value of n is guaranteed to be 3 after the second line executes.
Answer: False.
Explanation: Some compilers may give the value 3. The result of such code is dependent
on the compiler implementation. The C++ Standard says such code is illegal, and the
Standard says the results are undefined, meaning the compiler can do anything with it
that suits the compiler writer. One of my compilers gives the value 4 to n.
14. If we execute the code fragment in an otherwise complete, correct program:
n = 1;
cout << n++ << " " << n++ << " " << n++ << endl;
the output is guaranteed to be 1 2 3.
Answer: False.
Explanation: The code is illegal because its execution depends on the order of evaluation
of arguments. Various compilers give different answers. One compiler this writer uses
gives 3 2 1.
15. C++ uses only /* */ for comments.
Answer: False.
Explanation: C++ uses /* */ comments and // “here to the end of the line”
comments.
16. A program’s comments should connect the program code to the problem being
solved.
Answer: True.
Explanation: The purpose of comments in a program is to help the human reader of the
code to connect the program to the problem being solved. Comments are so important
there is an aphorism, often quoted by expert programmers: “If the comments and the code
disagree, then both are probably wrong.
17. A program should have a comment on every line.
Answer: False.
Explanation: This would be satisfactory only on a very complicated assembly language



©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.

Get to know the seller

Seller avatar
Reputation scores are based on the amount of documents a seller has sold for a fee and the reviews they have received for those documents. There are three levels: Bronze, Silver and Gold. The better the reputation, the more your can rely on the quality of the sellers work.
ExamsExpert (self)
Follow You need to be logged in order to follow users or courses
Sold
629
Member since
2 year
Number of followers
313
Documents
2838
Last sold
16 hours ago
ExamsExpert

We as a team provide best and Latest Test Banks that helps students to get A Grade we have vast range of test banks you can order us any test bank that you need

4.5

87 reviews

5
60
4
15
3
9
2
1
1
2

Recently viewed by you

Why students choose Stuvia

Created by fellow students, verified by reviews

Quality you can trust: written by students who passed their tests and reviewed by others who've used these notes.

Didn't get what you expected? Choose another document

No worries! You can instantly pick a different document that better fits what you're looking for.

Pay as you like, start learning right away

No subscription, no commitments. Pay the way you're used to via credit card and download your PDF document instantly.

Student with book image

“Bought, downloaded, and aced it. It really can be that simple.”

Alisha Student

Frequently asked questions