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

Absolute C++ 5th Edition by Walter Savitch - Test Bank   Instant Download - Complete Test Bank With Answers     Sample Questions Are Posted Below   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 …

$19.99

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

 

Instant Download – Complete Test Bank With Answers

 

 

Sample Questions Are Posted Below

 

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.

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

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

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

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

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

  1. Consider the array declaration, int x[20];. There is no memory allocated for x[20].

Answer: True

Explanation: There is memory allocated for x[0] through x[19] but not for x[20]:

  1. Arrays in C++ may have several different types stored in them.

Answer: False

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.

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

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

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

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

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

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

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

  1. C++ arrays check for out-of-range index values.

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.

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

 

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

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

  1. In the array declaration

double score[5];

identify the following:

  1. The array name
  2. The base type
  3. The declared size of the array
  4. The smallest and largest index values this array can have.
  5. 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.

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

Answer:

int i, a[20];

for(i=0; I <20; I++)

cin >> a[i];

 

  1. Consider the declaration

double a[10] = {1.2, 2.1, 3.3, 3.5, 4.5, 7.9, 5.4,

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

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

  1. tripler(a[2]);
  2. tripler(a[3]);
  3. tripler(a[number]);
  4. tripler(a);
  5. 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.

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

  1. Nothing is wrong with either bit of code.
  2. There are not enough initializers for the array.
  3. There is an illegal index in the loop.
  4. There are too many initializers in for the array.
  5. 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.

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

 

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.

 

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

 

 

  • 0 1 2      3      4      5      6      7

|——|——|——|——|——|——|——|-

  • 8 6 10     2      16     4      18     14

 

 

 

  • 0 1 2      3      4      5      6      7

|——|——|——|——|——|——|——|-

 

 

 

  • 0 1    2      3      4      5      6      7

|——|——|——|——|——|——|——|-

 

 

  • 0 1 2      3      4      5      6      7

|——|——|——|——|——|——|——|-

 

 

  • 0 1 2      3      4      5      6      7

|——|——|——|——|——|——|——|-

 

 

  • 0 1 2      3      4      5      6      7

|——|——|——|——|——|——|——|-

 

 

  • 0 1 2      3      4      5      6      7

|——|——|——|——|——|——|——|-

 

 

  • 0 1 2      3      4      5      6      7

|——|——|——|——|——|——|——|-

 

Answer:

Exercise the Selection Sort Algorithm:

 

X = start of terminal segment

 

  • 0 1 2      3      4      5      6      7

X——|——|——|——|——|——|——|-

  • 8 6 10     2      16     4      18     14
  • ^

smallest in the segment

swap with #0

move start of segment to index #1

  • 0 1 2      3      4      5      6      7

|——X——|——|——|——|——|——|-

  • 2 6 10     8      16     4      18     14

^

smallest in the segment

swap with #1

move start of segment to index #2

  • 0 1 2      3      4      5      6      7

|——|——X——|——|——|——|——|—-

  • 2 4 10     8      16     6      18     14
    • ^

smallest in the segment

swap with #2

move start of segment to index #3

 

 

  • 0 1 2       3      4      5      6      7

|——|——-|——-X——|——-|—–|——-|–

  • 2 4 6       8      16      10    18      14
    • ^

smallest in the segment

swap with #3

move start of segment to index #4

 

  • 0 1 2       3       4      5      6      7

|——|——-|——-|——-X——-|——|—–|-

  • 2 4 6       8       16      10     18    14
    • ^

smallest in the segment

swap with # 4

move segment to index  #5

 

  • 0 1 2       3       4       5      6      7

|——|——-|——-|——-|——-X——|——|-

  • 2 4 6       8       10      16     18     14

^

smallest in the segment

swap with # 5

move seg to index  #6

 

  • 0 1 2       3      4      5      6      7

——-|——-|——-|——|——|——X——|-

  • 2 4 6       8      10     14     18     16

^

smallest in the segment

swap with #6

move seg to index  #7

  • 0 1 2       3      4      5      6      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

 

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

 

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.

}

}

 

  1. Insert const before .any of the following array parameters that can be changed to

 

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.

 

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.

  1. 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[2] << endl;

a[1] = a[2];

cout << a[0] << ” ” << a[1] << ” ”  << a[2] << endl;

}

 

Answer: The output is:

1.1 3.3 2.2

1.1 2.2 2.2

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.

  1. What is the problem with this code?

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.

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

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

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 C++ array indices, that is subscript values, must be
    1. An integer type
    2. Non-negative
    3. Positive
    4. Less than or equal to the declared size of the array
    5. 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.

  1. Given the array declaration, int a[20]; The first element is written as:
    1. a[1]
    2. a[0]
    3. a
    4. a[20]
    5. 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 .

  1. Given the array declaration, int a[20]; The last (legal) element is written as:
    1. a[2]
    2. a[0]
    3. a
    4. a[20]
    5. 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 .

  1. Are the following array initializations correct? If not, why not?
    1. int x[4] = {8, 7, 6, 5, 4};
    2. int x[] = {8, 7, 6, 5, 4};
    3. int x[4] = {8, 7, 6};
    4. const int SIZE =4;

int x[SIZE];

  1. const int SIZE =4;

int x[SIZE-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?)

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

  1. names a copy of the array argument.
  2. refers to exactly the same array as the calling program
  3. is passed the address of the argument, and the function needs further information about the array size to safely use an array parameter
  4. 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.)

 

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

  1. i) When your program runs, how much memory is required for this array?
  2. 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?

  1. 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.
  2. 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
  3. 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
  4. 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.)

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

  1. okceg
  2. gecko
  3. ecko followed by a character from an out of bounds access.
  4. kceg followed by a character from an out of bounds access.
  5. Correct answer not listed. Specify what the output is.

Answer: b)

Explanation: a) traverses the array in the opposite direction than the code specifies. c) presumably starts at the 4th position maybe because it counts 1 as the first array item, so runs so off the end of the array. This one does run in the right direction. d) is like c) but it runs the wrong direction.

  1. Consider the function definition and array declarations. Which are incorrect calls to the function make_2? Why?

(In considering this code, you are to ignore the a) b), and so on, at the start of the lines, and consider that this code is to be embedded in a complete and correct program.)

 

void make_2 ( int a[], int size )

{

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

a[i] = 2;

}

int array1[20];

  1. make_2( array, 30 );
  2. make_2( array, 10 );
    >>>>>replace array with array1 two places
  3. “Hey, make_2, come change array1. Its size is 20.”

 

//A declaration for parts e) through h).

int array2[50];

  1. make_2( array2, 50 );
  2. make_2( array2[5],50 );

 

Answer: b) and d) are correct.

Explanation: a) the size argument is too large c) This is not a call to make_2, it is a string constant. e) nets a warning that an int has been passed to a pointer parameter without a cast.

 

  1. Given the definition and code fragment:

int matrix[2][3];

int k = 0;

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

for (int j=0, j < 4; j++)

matrix[i][j] = k++;

The value of matrix[0][0] is

  1. 0
  2. 1
  3. 2
  4. 3
  5. 4

Answer: a) 0

Explanation: The outside loop, at the start, i=0, and in the inside loop, at the start, j=0. This is the first time the expression k++ is encountered. The value of this expression is 0. Hence, matrix[0][0] is 0.

  1. Which of these array definitions will set all the indexed variables to 0?
    1. int array[5];
    2. int array[5] = {0};
    3. int array[5] = {0,1,2,3,4};
    4. int array[5] = {0,0,0};x
      >>What is the x?
    5. int array[5] = {0,0,0,0,0};x

>>What is the x?

Answer:  b), d) and e)

Explanation: b) and d) explicitly initialize some of the indexed variables to 0. The rest are automatically set to 0. Part a) leaves the indexed variables with garbage in them. Part c) sets array[0] to 0, array[1] to 1, array[2] to 2, etc.

Additional information

Add Review

Your email address will not be published. Required fields are marked *