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

<< Test Bank For Absolute Java 5th Edition by Walter Savitch Test Bank For Young Family Focused Nursing Care By Denham Eggenberger >>
Product Code: 222
Availability: In Stock
Price: $24.99
Qty:     - OR -   Add to Wish List
Add to Compare

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

Description

 

WITH ANSWERS
Absolute C++ 5th Edition by Walter Savitch  
Test Bank 

 

Chapter 2 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:
  1. The if, while and for statements control only one statement.

Answer: True

Explanation: The one statement may be a block (statements that are enclosed with curly braces { }) or a simple statement.

  1. Given the declaration

int x = 0;

The following expression causes a divide by zero error:

(x !=0) || (2/x < 1);

Answer: False.

Explanation: The || operator uses short-circuit evaluation. The first member of this expression is true; the truth value of the complete expression can be determined from this; consequently, the second expression is not evaluated. There is no divide-by-zero error.

  1. Suppose we have these declarations,

int x = -1, y = 0, z = 1;

This Boolean expression is correct and it does what the programmer intends.

x < y < z

Answer: False

Explanation: Unfortunately, the expression compiles without error and runs. The < operator associates (groups) left to right, so the expression evaluates as

(x < y) < z

The left hand expression evaluates to true, which, if compared to a numeric type, converts to 1. When compared to 1, this is false. What the programmer intends, expressed as mathematacs might is -1 < 0< 1, a result that is clearly true.

  1. You want to determine whether time has run out. The following code correctly implements this.

!time > limit

Answer: False.

Explanation: The expression always evaluates to false. This cannot be what the programmer intended. The compiler doesnt catch the problem because the code is legal, correct C++. Corrected code is !(time > limit)

Code execution proceeds as follows: The operator ! takes a bool argument. It returns the opposite bool value. The value of time is converted to a bool. The value of time is certainly nonzero, hence !time is !true, i.e., false. The > compares this result with a numeric value, limit, (an int or perhaps some kind of floating point). The value on the left (false) is converted to a 0 value of that type. The value of limit is unlikely to be a negative number and we are concerned about time running out, so it is unlikely that time is zero. Consequently, the inequality becomes 0>limit, where limit is nonzero. This is false.

  1. The value of count is 0; limit is 10. Evaluate:

(count == 0)&&(limit < 20)

Answer: true

  1. The value of count is 0; limit is 10. Evaluate:

count == 0 && limit < 20

Answer: true

Explanation: The operators == and < have higher precedences than &&, hence the expressions, count == 0 and limit < 10 are evaluated (to true) then the && is executed.

  1. The value of count is 0; limit is 10. Evaluate:

(count != 0)||(limit < 20)

Answer: true.

Explanation: The first expression evaluates to false, the value of the || expression is determined by the second expression. The second expression is true so the || expression evaluates to true.

  1. In a while loop, the Boolean_Expression is executed before each execution of the loop body.

Answer: true

  1. In a do-while loop, a continue statement terminates the loop.

Answer: False

Explanation: The continue statement causes the Boolean_Expression to be executed. If true, the body executes, otherwise the loop terminates.

  1. A break statement is used in loops only.

Answer: False.

Explanation: In addition to its use in loops, a break statement is used in the switch statement to transfer control to the next statement after the switch block.

  1. When a loop is nested in side another loop, a break or continue statement terminates or restarts the outermost loop of the nested loop structure.

Answer: False

Explanation: A break or continue terminates or restarts only the innermost loop containing the break or continue.

 

Free Form Questions:
  1. Assume variables first and second are declared to be double and are initialized. Write a sequence of lines of code that cause the values stored in first and second to be exchanged if the value of first is not less than second.

Answer:

// double first, second;

// these have been initialized

if (!(first < second))

{

double temp = first;

first = second;

second = temp;

}

//assert: first <= second

  1. Write multiway if-else statements for which the output is Alarm: Boiler Pressure: TOO HIGH if the value of the variable boiler_pressure is greater than 1000 (psi), and the output is Boiler Pressure: TOO LOW if the value of boiler_pressure is below 100(psi), otherwise the output is Boiler Pressure: within normal limits.

Answer:

if (boiler_pressure > 1000)

cout << Boiler Pressure: TOO LOW ;

else if (boiler_pressure < 100)

cout << Boiler Pressure: TOO LOW ;

else

cout << Boiler Pressure: within normal limits. ;

  1. Write multiway if-else statements in which letter grades are assigned based a numeric grade based on this ten point scheme:

if the numeric grade is not less than 90, the letter grade is an A,

if the numeric grade is not less than 80, the letter grade is a B,

if the numeric grade is not less than 70, the letter grade is C,

if the numeric grade is not less than 60, the letter grade is D,

otherwise the letter grade is F.

Answer:

if (numeric_grade >= 90)

letter_grade = A;

else if (numeric_grade >= 80)

letter_grade = B;

else if (numeric_grade >= 70)

letter_grade = C;

else if (numeric_grade >= 60)

letter_grade = D;

else

letter_grade = F;

  1. Assume variables first, second, and max are declared to be double and are initialized. Write a sequence of lines of code that cause the larger of the values in first and second to be stored in max.
    Answer:

//double first, second, max

//first and second have been initialized

if ( (first < second) )

max = second;

else

max = first;

//assert: max >= first && max >= second

  1. A numeric integer grade is between 50 and 99. Using integer division or otherwise obtain a int value that is 5, 6, 7, 8, or 9 from the numeric grade. Write code using a switch statement using this number in the selector expression that assigns letter grades based on this 10 point scheme:

if the numeric_grade is not less than 90, the letter_grade is an A,

if the numeric_grade is not less than 80, the letter_grade is a B,

if the numeric_grade is not less than 70, the letter_grade is C,

if the numeric_grade is not less than 60, the letter_grade is D,

otherwise the letter_grade is F.

Answer:

int value = numeric_grade/10;

switch(value)

{

case 9: letter_grade = A;

break;

case 8: letter_grade = B;

break;

case 7: letter_grade = C;

break;

case 6: letter_grade = D;

break;

default: letter_grade = F;

break;

}

  1. Write Boolean expressions that represent the given English expressions. Assume any variables used have been declared and initialized.
  2. a) alpha is greater than 1
  3. b) x is odd
  4. c) x and y are odd
  5. d) ch is an upper case alphabetic character (between A and Z).
  6. e) digit, which is f type char, has value that is indeed a digit.

Answer:

  1. alpha > 1
  2. (x%2==1)
  3. (x % 2==1) && (y % 2==1)
  4. (A <= ch) && (ch <= Z)
  5. (0 <= digit) && (digit <= 9)
  6. Write Boolean expressions that represent the given English expressions. Assume any variables used have been declared and initialized.
    1. at least one of x or y is odd
    2. at least one of x or y is non-negative (x is non-negative is written x >= 0)
    3. The hit is no more than 2.5 units away from target
    4. x is 1 or x is equal to y
    5. t is strictly between 3.2 and 3.3

Answer:

  1. (x%2==1) || (y%2==1)
  2. (x >= 0) || (y>=0)
  3. ((hit target) <= 2.5 ) && ((hit target) <= -2.5)
  4. (1==x) || (x==y)
  5. (3.2 < t) && (t < 3.3)
  1. Explain the programmers saying from the text, section 2.2, Garbage in means garbage out.

Answer: This remark means that if you supply a program with bad data, you are guaranteed useless results from your program.

  1. Use the condition operator (x?y:z) to write a very compact expression that assigns the maximum of variables n1 and n2 to the variable max. You should assume that any variables you use have been declared and initialized appropriately.

Answer: max = (n1>n2) ? n1 : n2;

Explanation: The parentheses are present only for readability. That the > operator has higher precedence makes the parentheses unnecessary.

  1. What is the output from each of the following loops?
    1. while ( 0 )

cout << X;

cout << endl;

  1. do

cout << X;

while ( y != y );

cout << endl;

  1. int i = 1;

while (i < 9)

{

cout i;

i++;

}

cout << endl;

  1. char c = A;

do

{

cout << c << ;

c = c + 2;

} while ( c <= M )

cout << endl;

  1. int i = 0;

while (i < 50)

{

if ( i < 20 && i != 15 )

cout << X;

i++;

}

cout << endl;

Answer:

The output of each loop is:

  1. The only output is a carriage return.
  2. X
  3. 12345678
  4. A C E G I K M
  5. XXXXXXXXXXXXXXXXXXX (There are 19 X)
  6. Write the following do-while statement with a while construct, and maybe some extra code.

x = 10;

do

{

cout << x << endl;

x = x 3;

} while ( x > 0 );

 

Answer: A simple minded change from do while to while and insertion of the loop body gives this:

x = 10;

cout << x << endl;

x = x 3;

while ( x > 0 )

{

cout << x << endl;

x = x 3;

}

A look at the code suggests that the following is somehow smarter

x = 10;

while ( x > 0 )

{

cout << x << endl;

x = x 3;

}

  1. Write a program that reads in exactly 10 integers and outputs the sum.

Answer:

#include

//loop to accept 10 integers and sum

int main()

{

using namespace std;

int x, sum = 0;

cout  << Enter 10 integers, each followed by

<< I will give the sum. << endl;

for(int i =0; i < 10; i++)

{

cout << Enter integer << i << : ;

cin >> x;

sum = sum + x;

}

cout << sum: << sum << endl;

return 0;

}

  1. Write a program that reads in and sums the squares of positive integers until a value that 0 or less is read in.

Answer:

// file ch2nu36.cc

// test question 36 for chapter 2

>>Delete above comment

#include

using namespace std;

 

//loop to accept positive integers until nonnegative

//integer, then return sum

int main()

{

int x = 1, i = 0, sum = 0;

cout << Enter positive integers, followed by

<< 0 or negative stops. << endl

<< I will give the sum. << endl;

while ( x > 0 )

{

cout << Enter integer << i << : ;

cin >> x;

sum = sum + x;

i++;

}

cout << sum: << sum << endl;

return 0;

}

  1. For each of the following situations, tell which type loop (while, do-while, or for) would be best in that situation:
    1. Reading a list of an unknown number of homework grades for a single student.
    2. Summing a series such as 1 +1/2 +1/(22) + 1/(23) + + 1/(28)
    3. Testing a newly coded library function to see how it performs for different values of its arguments.
    4. Reading in the number of days of vacation taken by an employee.

Answer:

  1. A while loop because the list of grades may be empty.
  2. A for loop, because the length of the list of numbers is known.
  3. A do-while loop could be used since there will be at least one value tested.
  4. A while loop because the list of grades may be empty.
  1. Predict the output of the following nested loops:

int n = 1;

while(n <= 10)

{

int m = 10;

while(m>=1)

{

cout << n << times << m

<< = << n*m << endl;

m;

}

n++;

}

Answer: The output is a multiplication table

1 times 10 = 10

1 times 9 = 9

. . .

1 times 1 = 1

2 times 10 = 20

. . .

2 times 1 = 2

3 times 10 = 30

. . .

3 times 1 = 3

4 times 10 = 40

4 times 9 = 36

. . .

4 times 2 = 8

4 times 1 = 4

. . .

9 times 10 = 90

. . .

9 times 1 = 9

10 times 10 = 100

. . .

10 times 1 = 10

 

  1. Rewrite the following while loops as for loops:
    1. int i = 1;

while(i<=10)

{

if (i<5 && i !=2)

cout << X;

i++;

}

 

  1. int i =1;

while(i<=10)

{

cout << X;

i = i + 3;

}

  1. int n = 100;

do

{

cout << X;

n = n + 100;

}while(n < 1000);

Answer:

  1. for( int i=1; i<=10; i++)

if (i<5 && i !=2)

cout << X;

  1. for(int i=1; i<=10; i = i + 3)

cout << X;

  1. for( int n = 100; n <1000; n = n + 100)

cout << X;

 

Multiple Choice

There may be more than one correct answer. You must give all correct answers for full credit. An explanation is required.

  1. Which control construct repeats a sequence of statements zero or more times?
    1. while statement
    2. do-while statement
    3. for statement
    4. switch statement
    5. if-else statement

Answer: a), c)

Explanation:: b) repeats  1 or more times, d)  and e) are selection statements

  1. What is the value of the bool valued expression, 1 < x < 10? Does the value of this depend on the value of x? Explain, and give the expression that the programmer probably meant.
    1. This statement is incorrect as it is always false.
    2. This statement is correct and its value depends on x.
    3. This statement is incorrect and it is always true
    4. This statement is incorrect, but it does depend on the value of x.

Answer: c) This expression is always true. The value does not depend on x.  This is the mathematicians shorthand for what the programmer probably meant:

(1 < x)&&(x < 10)

Explanation: The < operator associates (groups) left to right, so the expression evaluates as (1 < x) < 10. The expression (1 < x) evaluates to either false or true, regardless of x. These bool values convert to int values 0 or 1 when compared to int value 10. The expression evaluates to true for all values of x.

  1. Which of the following is true of the && operator?
    1. It has two operands.
    2. It can have one operand.
    3. It uses short circuit evaluation.
    4. It is the logical AND operator.
    5. It returns true if either operand is true.

Answer: a), c), and d).

Explanation: b) is a wrong number of argments, e) is the OR command.

  1. Which of the following is true of the || operator?
    1. It has two operands.
    2. It can have one operand.
    3. It is the logical OR operator.
    4. It returns true if either operands is true.
    5. It uses short circuit evaluation.

Answer: a) c) d) and e)

Explanation: b) is a wrong number of operands

  1. In a switch statement, when a break statement is encountered, an immediate transfer of control is made to
    1. the default case of the switch statement
    2. a goto statement
    3. the else clause
    4. the statement beyond the end of the switch
    5. none of these

Answers: d)

  1. An assignment of the value of a conditional expression to a variable (x =y?z:w;) can always be replaced by
    1. a switch statement with assignment statements for its case
    2. one or more ifs with else clauses and assignment statements for its true and false clauses.
    3. one or more nested while loops with assignments for the bodies of the loops.
    4. one or more ifs without any else clauses and assignment statements for its yes_statement(s).
    5. none of these is correct.

Answer: a), b), c) and d)
Explanation: c) is correct too, though strange. Here is one solution:

 

#include

using namespace std;

int main()

{

int x , z = 10, w =-10;

bool y = true;

while( y || (x = w))

{

while (y)

{

x = z;

break;

}

break;

}

cout << x << endl;

 

y = false;

while( y || (x = w))

{

while (y)

{

x = z;

break;

}

break;

}

cout << x << endl;

return 0;

}

/* Output is:

10

-10

*/

  1. In distinguishing an expression as true or false, C++ sees which of the following as true?
    1. true
    2. 0
    3. 1
    4. Any non-zero value
    5. The character F

Answer: a), c), and d) e) F is coerced char to bool, perhaps through an intermediate type

  1. Which of the following determines the operator that is processed prior to another operator?
    1. Operator associativity
    2. Operator precedence
    3. Whether the operator is an arithmetic operator
    4. None of these determine the order in which operators are processed.

Answer:  b)

  1. The following program purports to sum all entered int values that are greater than 5. It compiles without any error message, and it executes without error message, but nevertheless is wrong. Name all the errors.

// Display the sum of all entered int values

// greater than 5

#include

int main()

{

using namespace std;

int x, sum;

while (x < 10)

{

cin >> x;

if (x > 5);

sum = sum +x;

}

cout << The sum is values > 5 is << sum << endl;

}

  1. The while header needs a semicolon at the end of its line.
  2. The semicolon at the end of the if statement is an error that the compiler should catch.
  3. The semicolon at the end of the if statement causes all entered values to be summed.
  4. The sum variable is not initialized, so the output value is most likely garbage.

Answer: c) and d) are the errors. (Perhaps the user should have been prompted.)

  1. Which of the following loop statements is guaranteed to iterate the body of the loop at least once?
    1. while(control) body;
    2. do body while(control);
    3. for (initialize; test; update) body;
    4. none of the above
    5. all of the above

Answer: b)

  1. A switch statement must have
    1. a default case
    2. more than one non-default case
    3. a break statement
    4. none of the above
    5. all of the above

Answer: d)

  1. An enumeration type
    1. is type whose values are defined by a list of constants of type int.
    2. is a type separate from any of the integer types
    3. can be converted to integer types
    4. is a type that a programmer should avoid doing arithmetic with.

Answer: all, a), b), c), and d), are correct.

  1. The comma operator
    1. is a list of expressions separated by commas
    2. according to the ANSI C++ Standard, is supposed to be evaluated left to right
    3. not all compilers evaluate left to right, i.e., do not follow the C++ Standard, hence left to right evaluation should not be depended upon.
    4. has value equal to the value of the first expression in the list.
    5. all of the above

Answer: a) b) c).

Explanation: d) is wrong, the correct statement is: A comma expression has value equal to the value of the last expression in the list.

  1. Where is it legal to put a continue statement? What does the continue statement do there?
    1. A continue statement causes an unnested loop to restart.
    2. A continue statement causes a loop to halt.
    3. A continue statement in a loop nested in another loop causes the entire nested loop to restart.
    4. A continue statement in switch statement transfers control to the top of the switch.
    5. A continue statement in a nested loop causes that loop to restart, there is no effect on other loops.

Answer: a) e) are correct.

  1. Where is it legal to put a break statement? What does the break do there?
    1. A break is placed in a simple (unnested) loop, to terminate the loop.
    2. A break is placed in an inner block of nested blocks, to transfer control beyond the end of block the break is within.
    3. A break is placed in a loop in nested loops, to transfer control beyond the end of the innermost loop the break is within.
    4. A break is placed in a switch statement, to terminate the switch by transferring control beyond the end of the switch.
    5. A break is placed in a loop where it restarts the loop.

Answer: a) c) d) are correct

  1. If this code fragment were executed in an otherwise correct and complete program, what would the output be? Explain.

int a = 3, b = 2, c = 5

if (a > b)

a = 4;

if ( b > c)

a = 5;

else

a = 6;

cout << a < endl;

  1. 3
  2. 4
  3. 5
  4. 6
  5. None of the above, the cout statement belongs to the else and so is skipped.

Answer: d)

Explanation: The else belongs to the second if, despite indentation suggesting otherwise. Consequently, the first if statement executes, a is assigned the value 4, the second if executes, b is 2, c is 5, so b > c, evaluates to false so the else clause executes, so that a is assigned the value 6.

  1. Here is a collection of if and if-else statements with semicolons in various places. Assume all variables have been declared and initialized. Which of these are correct and are likely to give the programmers intent? Which are correct but unlikely to give the programmers intent? Give the error for the remaining.
  2. a) if ( a > b );

a = b;

else

b = a;

  1. b) if(a > b )

a = b;

else;

b = a;

  1. c) if(a > b )

a = b;

else

b = a;

  1. d) if(a > b)

a = b

else

b = a;

  1. e) if( x !=0 )

a = a / x

Answer: c) is correct and is likely to be the programmers intent. b) compiles but is unlikely to be the programmers intent.

Explanation:

  1. Compiler error: The semicolon at the end of the if line introduces a null statement, making the else keyword an error. The error will not be detected by the compiler until the else is encountered.
  2. Compiles with no errors, but is unlikely to do what the code author intended: The indentation suggests that the programmer meant the a=b and b=a lines to be alternatives chosen based on whether a>b. The semicolon at the end of the else causes the statement that appears to be the else clause always to be executed.
  3. correct, and apparently does what the programmer intended.
  4. Here the compiler will find an error at (or after) the else, since this is the first token after the assignment a=b, where a semicolon is needed.
  5. This is the same error as in d), but the error will be detected at or after the last x on the second line.
  1. Here is a collection of while and do-while Identify:
  2. those that are correct, and are likely to give the programmers intent;
  3. those that are correct, but unlikely to give the programmers intent, and

iii. what compiler error will the rest generate?

Assume all variables have been declared, but not necessarily initialized.

  1. cin >> n;

while (-1 != n)

{

sum = 0;

sum = sum + n;

}

  1. cin >> value;

while ( value != -1 )

sum = sum + value;

cin >> value;

  1. cin >> n;

int i = 1,
>>Semicolon not comma

while ( i < n );

sum = sum + i;

i++;

  1. cin >> count >> limit;

do

count++

while ( count * count > limit );

  1. cin >> x;

do

x++;

while( x > x );

Answer:

  1. This compiles. It is unlikely to be what the programmer intended. What the intent might be is hard to guess, since the value of sum is reset to 0 each time the loop executes.
  2. This compiles. The indentation suggests that the programmer intended the two lines following the to be in the body of the loop. The second of these is not controlled by the while clause, resulting in an infinite loop .
    >>Something is wrong. Maybe the indentataion??
  3. This compiles. There are two intent errors evident: the semicolon on the second line and the missing braces. If the loop is entered, this is an infinite loop, since the statement controlled by the loop is the null statement inserted by the semicolon on the second line changes neither i nor n. The intent evidently was to run the loop n or n-1
  4. The syntax error is a semicolon missing from count++.
  5. This compiles, but the loop executes its body only once. It is difficult to guess what the programmers intent might have been, but this probably isnt it!
  1. If the following code fragment is executed in an otherwise complete and correct program, which expression will be executed? Why?

x = 0;

if (x = 12)

yes_statement;

else

no_statement;

  1. The no_statement will be executed because x is not 12.
  2. The statement has incorrect syntax so will not compile at all.
  3. x=12 is illegal in the Boolean expression of an if
  4. The yes_statement will be executed.

Answer: d)

Explanation: The expression x = 12 has the value 12, which is converted to true, causing the if always to execute the yes_statement.

  1. Which of the following control structures requires curly braces?
    1. if-else
    2. while
    3. do-while
    4. switch
    5. for

Answer: d)

Explanation: The other control constructs operate on a single statement, which may be, but is not required to be, a compound statement.

  1. In the expression (j > 0 && j+1 == 10), which operator executes last?
    1. >
    2. &&
    3. +
    4. ==

Answer: b)

Explanation: The precedences, higher to lower are: +, >, ==, &&. So the order is j+1, j>0, then (j+1)==10, then (finally) the ((j>0) && ((j+1) == 10))

  1. When you dont recall operator precedences you can
    1. Look in a table of precedences
    2. Guess
    3. Use parentheses
    4. Experiment with the compiler

Answer: c) is perhaps best and easiest, but a) and d) are reasonable if you arent taking an exam.

  1. Consider the if statement:

if(condition) yes_clause; else no_clause;

Under which of the following circumstances will both the yes_clause and the no_clause will be executed?

  1. When the condition is true.
  2. When the condition is false.
  3. When the condition is ambiguous.
  4. This will not happen.

Answer: d)

  1. The following are true about the expression left && right.
    1. The expression is false when left is false and right is false
    2. The expression is true when left is true and right is false
    3. The expression is false when left is false and right is true
    4. The expression is true when left is true and right is true

Answer: a) c) and d)

  1. The following are true about the expression left || right.
    1. The expression is false when left is false and right is false
    2. The expression is true when left is true and right is false
    3. The expression is false when left is false and right is true
    4. The expression is true when left is true and right is true

Answer: a) b) and d)

  1. The statements int x = 1; int y; y = x++;
    1. Assign y the value 2;
    2. Change the value of x to 2.
    3. Assign y the value 0;
    4. Assign y the value 1;
    5. The ++ is a postfix operator.

Answer:  b) d) and e)

  1. The statements int x = 1; int y; y = x;
    1. Assign y the value 1;
    2. Change the value of x to 0
    3. Assign to y the value 1;
    4. Assign to y the value 0;
    5. The is a prefix operator.

Answer: b) d) and e)

  1. What is the output of the following, if it were embedded in an otherwise correct and complete program and run?

int x = 10;

while (x > 0)

{

cout << x << ;

x = x + 3;

}

cout << endl;

  1. 10 13 16 19 . . .
  2. The compiler detects that this will be an infinite loop, so it does not compile.
    Insert lowercase be
  3. This is an infinite loop. When compiled and run, it runs until machine limitations stop it, or you get tired of it and kill the process.
  4. 0 3 6 9.

Answer: a) and c)

  1. This question asks about nesting of if, if-else, switch, while, do-while, and for statements:
    1. These constructs may not be nested in at all.
    2. These constructs may be nested in any way that meets the needs of algorithms the programmer is coding.
    3. Only control constructs of a given kind may be nested (while loops within while loops; if-else within if-else)
    4. The question does not make sense in C++.

Answer: b) Control constructs may be nested arbitrarily.

  1. Each of the following has at least one error, either intent, or an error that may be caught by the compiler or both). What is the error? Assume all the variables you see are defined and initialized.
    1. for(int i = 0; i <10; i++);

sum = sum +x;

  1. if (x > 0)

x = 3

else

x =4;

  1. if(x = 0) x = MAXINT;
  2. if x > 0 x = 3;
  3. if (x>0) then x =3;

Answer: a) Not wrong, but the semicolon is probably an intent error. b) Semicolon missing in the yes_clause. c) The = probably should be ==.  d) needs parenthese to be correct C++. e) C++ does not use then as a keyword.  If we blindly fix the syntax, whatever the then might be, there needs to be a semicolon after it, and the sequence then; x=3; should probably be in curly braces. Actually, there no way to guess what the programmer might mean here. There is a good chance the programmer is a refugee from Pascal, and then should be deleted.

Chapter 4 Parameters and Overloading 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. There is only one kind of parameter passing in C++, namely call-by-value.

Answer: False.

Explanation: There is also call-by-reference. Call-by-value makes a copy of the argument then uses that, hence does not make changes to the argument. Call-by-reference effectively passes the argument hence can make changes to the argument.

  1. The call-by-reference mechanism is specified in the function declaration and definition, using a $ between the type and the parameter.

Answer: False

Explanation: The character is an ampersand, &, not a $. It is placed between the type and the parameter to indicate a call-by-reference parameter.

  1. The position of the ampersand in the function header is of no importance to the proper compiling and execution of code that uses call-by-reference parameters.

Answer: True

Explanation: It makes no difference whether the ampersand appears next to the type or the variable.

void example3(double  &ref_to_dbl);

void example3(double&  ref_to_dbl);

//In a call to this function ref_to_dbl becomes a

// reference to double that refers to the argument.

  1. A call-by-value parameter may pass data only into a function.

Answer: True. The value parameter is essentially a local variable initialized to the value of the argument at the time of a call.

  1. A call-by-reference parameter may pass data only out of a function.

Answer: False. The reference parameter is an alias for the callers argument. The mechanism is to pass the address of the argument which is used where the parameter occurs.  Hence, a reference parameter makes available to the function the initial and ongoing values of the callers argument as well as providing a mechanism for the function to change the callers argument.

  1. A program should have all of its functions written before testing can begin.

Answer: False.

Explanation: Functions that call other functions can be tested independently of the called functions by writing stub functions. Stub functions are very simple functions that do nothing much more than sending just enough data to the caller to allow testing..

  1. Functions that call other functions can be tested independently of the called functions.

Answer:. Functions that call other functions can be tested independently of the called functions by writing stub functions. Stub functions are substitute functions that are as simple as possible yet send data enough back to the caller to allow testing of the caller.

  1. Call-by-reference is restricted to void

Answer: False

Explanation: There is no connection between the return mechanism and the parameter passing mechanism.

  1. Names of parameters in functions, especially function prototypes, have no meaning, and may be selected quite arbitrarily.

Answer: True

Explanation: Technically true, nevertheless for the following reasons, names should be selected with care. (I accept an answer of false from a student who provides a good explanation.)Functions should be self-contained modules that are designed separately from the rest of the program. On large projects, different programmers may be assigned to write of different functions. The programmer must choose meaningful names else the fellow programmers will have more difficulty than necessary in understanding the code. That several functions may have the same parameter names is of no matter.

  1. Suppose a programmer supplies the ampersand for call-by-reference in a prototype, but forgets to put the ampersand in the definition. The compiler will nevertheless correctly interpret the programmers intent and compile the function.

Answer: False

Explanation:. The compiler compiles what the programmer writes, not the intent.

  1. There is no problem with these two function definitions:

void func(int x){/**/}

int func(double x){/**/ return something_double;}

Answer: True

Explanation: C++ allows function name overloading. C++ distinguishes the function by inferring a list of types from the argument list then matching this to lists of parameter types for the specified function name. This ignores the issue of coercion (automatic type conversions).

  1. There is no problem with the compiler distinguishing these two function definitions:

void func(double x){/**/}

int func(double x){/**/ return something_double;}

Answer: False

Explanation: C++ does not distinguish functions based solely on the return value.

  1. The compiler ha no problem distinguishing these two function definitions:

void func(double &x){/**/}

void func(double x){/**/}

Answer: False

Explanation: C++ does not distinguish functions based solely on call-by-value vs. call-by-reference.

  1. Mixing call-by-reference and call-by-value parameters is strictly prohibited.

Answer: False

Explanation: Whether a given parameter is call-by-value or call-by-reference depends on whether there is an ampersand present. It is perfectly legitimate to mix call-by-value and call-by-reference parameters.

  1. Default arguments can be used with either call-by-value or call-by-reference parameters.

Answer: False

Explanation: The text says [Default arguments] do not make sense for call-by-reference parameters. Suppose the function writes to the parameter. What does the parameter cause to be changed in the caller?

 

Free Form Questions:

 

  1. Write a void function using two type int call-by-reference parameters that swaps the values in the arguments. Be sure to include testable pre and post conditions.

Answer:

//precondition: arguments arg1, arg2 are initialized

//postcondition: arg1post == arg2pre && arg2post == arg1pre

void swap( int & lhs, int & rhs)

{

int temp = lhs;

lhs = rhs;

rhs = tmp;

}

  1. Carefully describe the call-by-value mechanism.

Answer: A call-by-value parameter is a local variable initialized to the value of the argument, which is computed at the time of the call.

  1. Write a definition for a void-function that has two int value parameters and outputs to the screen the product of these arguments. Write a main function that asks the user for these two numbers, reads them in, calls your function, then terminates.

Answer:

//file: testProblem.cc

//illustrates value parameters in a void-function,

//fetching values, and the calling of that function

//to multiply and display arguments.

#include

using namespace std;

void func(int x, int y)

{

cout << x * y << endl;

return;

}

int main()

{

int f, g;

cout << Enter two integers, Ill return the product.

<< endl;

cin >> f >> g;

func(f, g);

return 0;

}

  1. What does the function given here do when called if both the ampersands (&) are removed? Why?

void func(int& x, int& y)

{

int t = x;

x = y;

y = t;

}

Answer: Nothing. The function has no effect at all.

Explanation: With the parameters changed from reference to value, the function can do nothing. There is no effect external to this function. There are no changes are made to the callers arguments. The only changes are made to local variables and value parameters.

  1. The fundamental rule for testing functions requires that every function be tested in an already fully tested and debugged program. How can this be accomplished? Give a testing scenario for testing a program with main function that calls several functions.

Answer: The main function is tested with stub functions replacing each` function. Stubs should be small enough that their correctness is assured. Stubs return enough information to let the main function compile and run, so that it can be tested. Then test the main function. Having done this, each function in turn can be tested.

 

An alternative is to test the functions with driver functions. Drivers are functions that call the function to be tested. Drivers, like stubs, should be simple enough that their correctness is assured. Then the function is called and tested. Clearly the assumptions of small enough that correctness is assured are really questionable. However, this procedure is better than writing a 200 line program or worse a 2000 line program and then testing it.

  1. What is a driver program?

Answer:. Drivers are programs that call a function to be tested. Drivers should be simple enough that their correctness is assured.

  1. What is a stub?

Answer: A stub is a small function that replaces another as yet untested function. The stub allows the caller to be tested without the added complexity of the untested function.

  1. Write a stub for the following function prototype:

double root( double a, double b, double c, int i);

// Precondition: a != 0 and a, b, c are coefficients of

// a quadratic equation a*x*x + b*x + c = 0  The value

// of i is either +1 or -1 to choose which root.

// Postcondition: return value, x, satisfies the

// equation  a*x*x + b*x + c = 0

 

Answer:

#include

// stub functions example

double root(double a, double b, double c, int i)

{

using namespace std;

cout << executing function

<< double root(double, double, double)

<< endl;

return 2.0;

}

  1. Write a stub for the function whose declaration is given below. Do not write a program that calls this, just write the stub.

Hint: This is very short.

double yield (double pressure,

double density, double temp);

// Precondition: pressure is newtons per square meter

// density is in kilograms per cubic meter

// temp is in degrees Celcius

// Postcondition: Return value is the relative yield of

// a chemical process.It is a  number between 0 and 1.

// 0 means no output and 1 means ideal yield.

Answer:

// THIS IS JUST A STUB

double yield (double pressure,

double density, double temp);

{

return 0.25;  // Not correct, but

// sufficient for testing

}

 

  1. Consider the revised pizza buying program of Display 4.7. This program provides the following overloading for unitPrice functions for round and rectangular pizza:

double unitPrice(int diameter, double price);

double unitPrice(int length, int width, double price);

Suppose we are faced with the need for the unit price on a square pizza. The problem here is to devise in a natural way to overload unitPrice to compute the price per square inch of a square as well as a round pizza?

Answer: There is no nice way to do this. A simple minded approach is to write

double unitPrice(int edge, double price);

This attempt involves having two overloaded unitPrice function versions both of which have argument lists with types int and double, which results in an ability.

 

A student might overload using two doubles for arguments:

double unitPrice(double edge, double price);

This leads to the problem of remembering always to use a double for the size (edge length) of a  square pizza and an int for the size (diameter). This tends to be error prone.

 

We are faced with writing a function with a different name. (Of course, the easiest way to solve the problem of finding a unit price for a square pizza is to call the function for rectangular pizza, passing the edge size to the length and the width parameters, but that begs the question of this test question: how to overload in a natural way.)

  1. Define function signature:

Answer:  A functions signature is the functions name with the sequence of types as listed in the parameter list, including any const keywords, but not ampersands.

  1. Write a void function definition for a function called zeroBoth that has two call-by-reference parameters, both of which are variables of type int, and that sets the values of both variables to 0.

Answer:

void zeroBoth(int & n1, int& n1)

{

n1 =0;

n2=0;

}

Multiple Choice

There may be more than one correct answer. You must give all correct answers for full credit. An explanation is required.

  1. Consider the following function and code segment.

void One( int first, int & second )

{

first = 17;

second = first + 1;

}

int main()

{

// other code

int j = 4;

int k = 3;

One(j, k);

// other code ..

}

After the call to One(j, k); what are the values of j and k? Why?

  1. j == 4, k == 3;
  2. j == 17, k == 18;
  3. j == 4, k == 18;
  4. j == 17, k == 3;

Answer: c) j == 4, k == 18

Explanation: The first parameter is called by value, so the parameter first is assigned 4 by the call. The parameter first is immediately assigned in the function, but the first argument is not changed, hence, j==4.

The second parameter is call-by-reference, so when first + 1 is computed to be 18, and is assigned to second, second is changed, and the corresponding argument, k is changed, hence, k==18.

  1. Given the function, and the main function calling it: Which, if any, of the following choices is the output of the following code? What does this function do?

#include

using namespace std;

 

void func ( int& x, int & y)

{

int t = x;

x = y;

y = t;

}

int main()

{

int u = 3; v = 4;

//

cout << u << << v << endl;

func ( u, v )

cout << u << << v << endl;

//

}

  • 3 4

3 3

  1. 3 4

4 3

  • 3 4

3 4

  1. 3 4

4 4

  1. e) none of the above. If you choose this, you must specify the output.

Answer:. b)

Explanation: The code swaps the values stored in the callers arguments

 

  1. Given the function, and the main function calling it: What is the output of the following code if you omit the ampersand (&) from the first parameter, but not from the second parameter? (You are to assume this code is embedded in a correct function that calls it.):

#include

using namespace std;

 

void func(int & x, int & y)

{

int t = x;

x = y;

y = t;

}

int main()

{

int u = 3; v = 4;

//

cout << u << << v << endl;

func ( u, v )

cout << u << << v << endl;

//

}

  1. a) 3 4

3 3

  1. b) 3 4

4 3

  1. c) 3 4

3 4

  1. d) 3 4

4 4

  1. e) none of the above. If you choose this, you must specify the output.

Answer:  a)

Explanation: The first argument is not changed by the function. The second argument is changed to 3.

 

  1. Which of the following overloadings will be invoked by this call?

g(1,2);

  1. int g(int count, double value);
  2. void g(double value, int count);
  3. void g(int value, int count);
  4. Neither, the compiler cannot decide which of these to use.

Answer: c)

Explanation: The match is exact.

 

  1. Which of the following overloadings will be invoked by this call?

g(1.0,2.0);

  1. int g(int count, double value);
  2. void g(double value, int count);
  3. void g(int value, int count);
  4. Neither, the compiler cannot decide which of these to use.

Answer: d)

Explanation: The compiler tries to find an exact match, and there is none. Then the compiler tries to find a match using automatic type conversion. Part c) is excluded because use would result in two double to int conversions. The compiler says there is an ambiguity between a) and b).

  1. Which of the following function declarations with default arguments are correct?
    1. void g(int length, int width, int height = 1);
    2. void g(int length=1, int width, int height);
    3. void g(int length, int width=1, int height = 1);
    4. void g(int length=1, int width=1, int height);

Answer: a) and c)

Explanation: C++ allows default arguments. If a default argument is provided for a parameter, all parameters to the right of this must be provided with default arguments.

  1. An assertion
    1. is never more than just comment embedded in code
    2. are always easily and precisely stated with C++ syntax,
    3. is used to document and check correctness in programs
    4. is typically a precondition or postcondition for a function
    5. if converted to a Boolean statement, may be used with the library assert macro to test whether the assertion is satisfied at that point in the code.

Answer: All of these except a) and b) are true.

Explanation: a) is way too restrictive. b) is optimistic beyond dreams. An assertion may well be just a comment, but can be much more, as  c)-e) state. Assertions are used like this: If you know that some of variables in your program should have a specific values, or these variable should make an expression take on a value you know, you can write this out as a Boolean expression (as an assertion) and test it.

  1. If you put assert macros throughout your code, then
    1. You have to put up with the resulting inefficiency and program halts with messages indecipherable to the user until you edit your code to remove them.
    2. You can put #define NDEBUG in your code in the file just before the #include 
    3. With most command line compilers and IDEs (integrated development environment), you can define NDEBUG for the compile session by using an IDE menu option or you can use the compiler command line option DNDEBUG.

Answer: b) and c) are correct.

Explanation: a) is wrong. (And horribly pessimistic.) Easy options exist as pointed out in b) and c) to prevent the macros from being compiled into your code.

  1. The fundamental rule for testing functions requires that every function be tested in an already fully tested and debugged program. How can this be accomplished?
    1. Impossible! The main function must have all the functions it calls attached to get it to compile and run properly.
    2. The main function is tested with stub functions replacing each` function.
    3. Write drivers for the stub functions to test them.
    4. Add each non-stub function in turn for testing.
    5. Write drivers for the function implementations one at a time to test them independently.

Answer: b) d) and e) are correct.

Explanation: a) is unreasonably pessimistic. The stubs in b) should be short enough that their correctness may reasonably assumed, hence c) is unreasonable, if possible. In d) we add just one function at a time, and may need to change other stubs to vary data passed to successive functions. If inconvenient to have a main program to drive the function, a driver that provides typical data to a call is an alternative.

  1. The preprocessor directives used with the assertion macros is/are
    1. #include
    2. #define NDBUG
    3. #include
    4. #include
    5. #include

Answer: b) and c)

Explanation: c) is necessary to provide access to the macro definition so that you can say assert(x==y), and b) is necessary for turning these off without an error prone edit session.

  1. With regard to default arguments:
    1. Zero or more call-by-value parameters in a function may have default arguments.
    2. All value parameters must have default arguments.
    3. If a function has a reference parameter, no parameters to the left of the reference parameter may have default arguments.
    4. If a parameter is missing a default argument, no parameters to the left of this point may have a default argument.
    5. Reference parameters can have default arguments.

Answer: a) c) d) are correct.

Explanation: a) you may, but you dont have to have default arguments.  b) is clearly wrong, there is no mandate that all value parameters have default arguments. If there are reference parameters mixed in, as in c) then value parameters to the left of the reference parameter cannot have default arguments. d) follows from the rules that reference parameters cannot have default arguments and that if any variables are missing default arguments, variables to the left may not have them either. Part e) is clearly wrong. Default arguments for reference parameters make no sense.

  1. Which of these properties of testing using stubs and drivers are correct?
    1. Using drivers and stubs is a lot of work for not much gain.
    2. Using drivers and stubs avoids trying to debug a large program all at once.
    3. Testing the pieces is difficult to do in any significant way. You need the entire program to run a meaningful test.
    4. Drivers run the pieces individually. They are temporary. They can be minimal, without i/o, having only data generating code, and not doing much (except possibly validating) with the information they return.
    5. Stubs are short programs that are fairly easy to write. They return only minimum data necessary for the caller to be debugged.

Answer: b) d) e) are correct.

Explanation: This testing technique is essentially divide and conquer. You avoid testing a large program all at once, allowing the testing of the i/o routines, for example, with drivers to assure that they work properly.

  1. Which of these remarks about formal parameters is correct?
    1. A formal parameter is a kind of place holder that is filled with the argument at the time of call to the function.
    2. A call-by-value formal parameter is a global variable that is initialized to the value set just before the function is called.
    3. A call-by-reference formal parameter is modeled on a substitution mechanism. The argument should be an expression, not a variable, since there is never a need to assign such a variable.
    4. The & (ampersand) character is used to indicate call-by-reference. This is done by placing the & after the type name which is followed by the parameter name in the definition of the parameter in the function header.
    5. The argument corresponding to a call-by-value parameter cannot be changed by anything that happens in the function call.

Answer: a) d) e) are correct.

Explanation: b) a call-by-value formal parameter is a local variable that is initialized to the value of the argument at the time of the call. c) a call-by-reference parameter is modeled on a substitution mechanism. The behavior is as if the parameter were substituted in the body the function wherever the parameter is used. Fetching the value of the parameter fetches the value of the argument, assigning the parameter assigns the argument.

  1. Which of these remarks about overloading a function name is correct?
    1. C++ distinguishes between function overloaded implementations by examining differences in return types.
      C++ distinguishes between overloaded function versions by examining differences in the argument lists.
    2. C++ does not support function name overloading.
    3. To decide which version of overloaded functions, C++ looks first for an exact match in the argument list types and the parameter list types.
    4. If there is no match between the argument list types and the parameter list types C++ expects the programmer to supply type conversions to get a match.

Answer: b) and d)

Explanation: c) is wrong, as is e). In e) the correct answer is C++ uses automatic type conversions to find a match between the list of parameter types and the list of argument types

  1. Indicate which of these remarks about function parameters and arguments is correct.
    1. Arguments are listed in the function header between parentheses following the function name.
    2. The word parameter is sometimes used as shorthand for formal parameter.
    3. Formal parameters appear in a function call between parentheses following the function name.
    4. Arguments are something that is used to fill in a formal parameter.
    5. The first argument fills in the first formal parameter, the second argument fills in the second formal parameter and so on.

Answers: b) d) and e) are correct.

Explanation: a) should be: Formal parameters are listed between parentheses following the function name in the function header. b) is correct. c) should be: Arguments appear in a function call between parentheses following the function name. d) and e) are correct.

  1. Consider the function

void doStuff(int parValue, int& parRef)

{

parValue = 100;

cout << parValue  in call to doStuff  =

<< parValue << endl;

parRef =222;

cout << parRef  in call to doStuff  =

<< parRef << endl;

}

and consider the call, which we assume is in a complete and correct program

int n1 = 1, n2 =2;

doStuff(n1, n2);

  1. The call to doStuff results in the assignment n1 = 222;
  2. The call to doStuff results in the assignment n2 = 222;
  3. The call to doStuff results in the assignment n1 = 100;
  4. The call to doStuff results in the assignment n2 = 100;
  5. There is no effect on either of these variables..

Answer: b) is correct

Explanation: The parameter parRef is a reference parameter, the argument corresponding to this is n2. The function doStuff contains an assignment, parRef = 222; The function doStuff behaves the assignment n2 = 222; were executed.

  1. Why does this version of the swap function fail to work? Is there a fix?

void swap(int & lhs, int& rhs)

{

lhs = rhs;

rhs = lhs;

}

  1. Of course it works! Just look at it. It clearly swaps the two parameters!
  2. It fails because the programmer forgot to make the parameters call-by-reference.
  3. It fails OK, and we can fix it we can just reverse the order of the lines.
  4. It fails because the first line destroys the old value of lhs without saving it. Then both variables have the old value of rhs in them.
  5. To fix this, we must save the lhs value in a local variable before making the first assignment indicated, then instead of the second line, assign the rhs the value of the local variable:

int local = lhs;

lhs = rhs;

rhs = local;

Answer: d) and e) are the answer.

Explanation: a) is argumentum ad baculum argument by the stick. Shout it loud and it is the truth..  b) is incorrect, both parameters are call-by-reference.  c) reversing the order of the assignments does not fix the fundamental problem of irretrievably destroying data.

  1. Consider the function, where the programmer inadvertently left out the ampersand in the definition of parRef. What is the output of the code?

void doStuff(int parValue, int parRef)

{

parValue = 100;

cout << parValue  in call to doStuff  =

<< parValue << endl;

parRef =222;

cout << parRef  in call to doStuff  =

<< parRef << endl;

}

and consider the call, which we assume is in a complete and correct program

int n1 = 1, n2 =2;

doStuff(n1, n2);

cout << n1 after call to doStuff = << n1 << endl;

cout << n2 after call to doStuff = << n2 << endl;

 

  1. parValue in the call to doStuff = 100;
  2. Write a review

    Your Name:


    Your Review: Note: HTML is not translated!

    Rating: Bad           Good

    Enter the code in the box below:



     

    Once the order is placed, the order will be delivered to your email less than 24 hours, mostly within 4 hours. 

    If you have questions, you can contact us here