Absolute C++ 5th Edition By Walter Savitch – Test Bank

 

 

To Purchase this Complete Test Bank with Answers Click the link Below

 

https://tbzuiqe.com/product/absolute-c-5th-edition-by-walter-savitch-test-bank-2/

 

If face any problem or Further information contact us At tbzuiqe@gmail.com

 

 

Sample Questions

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 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 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 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)

1.    a) y = x3

2.    b) y <= |x|

 

     double x, y, z, area; //declaration for c) through e).

1.    c) z = x6

2.    d) z = area

3.    e) p =

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.

1.    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);

1.    b) #include <cstdlib>

using namespace std;

 

int y; int x = -23; // any value for x

y = abs(x);

// or

#include <math.h>

double y, x = -79.8; // any value for y

y = fabs(x);

1.    c) #include <cmath>

using namespace std;

double z, x = 2.6;

z = pow(x, 1.6);

1.    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);

1.    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.

3.    Write code that declares x, y, and z as double 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.

4.    a) round up

5.    b) round down

6.    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

Assume that math.h has been included, and that all variables have appropriate values.

double x, y, z;

1.    z = ceil(x/y);

2.    z = ceil(x/y-0.5);

3.    z = floor(x/y-0.5);

4.    z = floor(x/y+0.5);

5.    z = floor(x/y);

Answer:

1.    rounds up — to the next integer greater than or equal to x/y

2.    OK rounds to the integer nearest to x/y, exact 1/2 values round down

3.    not reasonable. x/y with value 1.25 gives 0 result.

4.    OK rounds to the integer nearest to x/y, exact 1/2 values round up

5.    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,

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 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:

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 Problem10.cc

Problem10.cc: In function `int f(int)’:

Problem10.cc:3: 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

1.    Both author and client must know the requirements on the parameter values

2.    Both client and author must know what the return value is to be,

3.    Only the author needs to know the implementation details.

4.    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 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);

}

14.  Write a function definition for a isDigit function that takes one argument of type char and returns a bool 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.

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.

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)

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.

c.     0*rand() + 2

d.    0*(RAND_MAX-rand())/RAND_MAX + 2

e.    ((RAND_MAX-rand())/static_cast<double>(RAND_MAX))*3 + 2

f.      (RAND_MAX-rand())/static_cast<double>(RAND_MAX)*5 -2

g.    rand()/static_cast<double>(RAND_MAX)*2 + 3

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.

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)

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));

1.    This is overkill, it would be sufficient to use the floor function alone.

2.    Adding 0.5 to number pushes the range up so floor can produce the correct rounding.

3.    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.

4.    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;

double sum = 0;

while( j >=  0)

{

sum += d;

-j;

}

return sum;

}

With arguments 7and 2.0

1.    returns 7*2

2.    returns 7+2

3.    returns 7!

4.    There is a syntax error in the program so it won’t run.

5.    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.

e.    Difference Library function declarations (sometimes definitions) come from #include <header> 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;

}

1.    The code will not compile.

2.    The code will compile and run. The output will be unchanged.

3.    The code will compile. For a zero number of customers the code would produce a divide by zero run-time error.

4.    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?

#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;

}

1.    NUM is a global variable.

2.    num is a global constant.

3.    value is local variable in the main function

4.    d is a local variable in the numTimes

Answer: c) and d) are correct.

Explanation: Answers a) and b) are reversed: NUM is a global constant, and num is a global variable.

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;

cout << “You entered “ << value

<< “ NUM times this is “ << numTimes(value)

<< endl;

return 0;

}

double numTimes(int x)

{

double d;

d = NUM * x;

return d;

}

1.    The variable x is a parameter in function numTimes

2.    The variable value is an argument in a call to numTimes.

3.    The line double numTimes(int x); is a function definition.

4.    The line return d; in the function numTimes is necessary.

5.    The lines of code are a function declaration:

double numTimes(int x)

{ . . .}

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.

 

Comments

Popular posts from this blog

Business and Administrative Communication A Locker 12th Edition – Test Bank

Crafting and Executing Strategy The Quest for Competitive Advantage Concepts Arthur Thompson 22nd Edition- Test Bank

Experience Human Development 13Th Edition By Diane Papalia – Test Bank