dataset
stringclasses
1 value
id
stringlengths
21
21
question
stringlengths
8
5.15k
choices
listlengths
4
4
answer
stringclasses
4 values
rationale
stringlengths
1
1.57k
canterbury_cs
canterbury_cs_0000100
What is printed when the following program runs? <pre lang="text/x-java">public class Main { public static boolean getTrue() { System.out.print("T"); return true; } public static boolean getFalse() { System.out.print("F"); return false; } public static void main(String[] args) { getTrue() || getFalse(); } } </pre>
[ "TF", "F", "T", "TT" ]
C
If the first operand for || is true, as is the case here, the second is not evaluated.
canterbury_cs
canterbury_cs_0000101
Kexin is hashing the values 9, 45, 22, 48, 38 into a hash table of size 20. Which hash function will give her no collisions?
[ "h(k) = k % 10", "h(k) = k / 10", "h(k) = (k % 10) + (k / 10)", "h(k) = (k % 10) - (k / 10)" ]
D
A will collide on the 48/38; B will collide with 45/48; C will collide with 9/45.
canterbury_cs
canterbury_cs_0000102
For the Insertion sort algorithm; what is its best case and worst case performance?
[ "Best: O(n) \n Worst: O(n<sup>2</sup>)", "Best: O(n)<br>Worst: O(n)", "Best: O(log<sub>2</sub> n)<br>Worst: O(n<sup>2</sup>)", "Best: O(n<sup>2</sup>)<br>Worst: O(n<sup>2</sup>)" ]
A
Insertion sort, if given an already sorted list, will still perform O(n) comparisons to ascertain the list is sorted. &nbsp;If the list is "reverse sorted," &nbsp;then the &nbsp;first pass will require 1 exchange. &nbsp;The second pass will require 2 exchanges, etc. &nbsp;Hence, in the worst case, O(n<sup>2</sup>) exchanges.
canterbury_cs
canterbury_cs_0000103
For the selection sort algorithm; what is its best case and worst case running time?
[ "Best: O(1)<br>Worst: O(n)", "Best: O(n)<br>Worst: O(n<sup>2</sup>)", "Best:&nbsp;O(log<sub>2</sub> n)<br>Worst:&nbsp;O(n)", "Best: O(n<sup>2</sup>) \n Worst: O(n<sup>2</sup>)" ]
D
Selection sort repeatedly runs the Find-largest algorithm as its helper function. &nbsp;So, regardless of the list's initial ordering, Find-largest will cost n-1 comparisons for the first pass, n-2 for the second, etc. &nbsp;Hence selection sort's run time performence is independent of the list's initial ordering: O(n<sup>2</sup>)
canterbury_cs
canterbury_cs_0000104
You see the expression <code>n = 100000</code> in some code that successfully compiles. What type can <code>n</code> not be?
[ "int", "short", "float", "double" ]
B
Shorts can only hold values in [-32768, 32767].
canterbury_cs
canterbury_cs_0000105
Suppose you try to perform a binary search on the unsorted array {1, 4, 3, 7, 15, 9, 24}. Which element will not be found when you try searching for it?
[ "7", "1", "9", "15" ]
D
The answer is 15. The first check will look at 7. 15 is greater than 7, so we search to its right. The second check will look at 9. 15 is greater than 9, so we search to its right. The third check will look at 24. 15 is less than 24, so we look to its left. However, our range has just been inverted and our searching stops, not having found 15.
canterbury_cs
canterbury_cs_0000106
Fill in the single missing line of code:<br><code>int p, *r, **q;</code> <pre lang="text/x-c">p = 27; r = &amp;p; </pre> // MISSING LINE<br><code>printf("The value is %d", **q); // prints 27.</code>
[ "*q = *r;", "q = &amp;r;", "**q = p;", "q = &amp;&amp;p;" ]
B
B gets q to point to r, which points to p.
canterbury_cs
canterbury_cs_0000107
What would be the performance of removeMin and insert methods in a priority queue if it is implemented by a sorted list?
[ "O(1) , O(1)", "O(1) , O(n)", "O(n) , O(1)", "O(n) , O(n)" ]
B
O(n) , O(1)
canterbury_cs
canterbury_cs_0000108
What is the value of j after this code is executed? int i = 6, j = 10; j += i;
[ "4", "6", "10", "16" ]
D
The value of variable i (6) is added to that of variable&nbsp; j (10) resulting in 16 as the&nbsp; new value of j
canterbury_cs
canterbury_cs_0000109
Suppose q is an instance of a queue that can store Strings, and I execute the following statements starting with q empty: <pre lang="text/x-java">1. q.enqueue("Sweden"); 2. q.enqueue("is"); 3. q.enqueue("my"); 4. String w = q.dequeue(); 5. String x = q.peek(); 6. q.enqueue("neighbor"); 7. String y = q.dequeue(); 8. String z = q.dequeue(); </pre> &nbsp; What is the value of z after executing these expressions in order?
[ "<code>\"Sweden\"</code>", "<code>\"is\"</code>", "<code>\"my\"</code>", "<code>\"neighbor\"</code>" ]
C
If we consider the contents of the queue after each expression (listing contents from head to tail), we have 1. ["Sweden"] 2. ["Sweden" "is"] 3. ["Sweden" "is" "my"] 4. ["is" "my"]&nbsp; (and w gets set to "Sweden") 5. ["is" "my"]&nbsp; (and x gets set to "is") 6. ["is" "my" "neighbor"] 7. ["my" "neighbor"] (and y gets set to "is") 8. [ "neighbor"]&nbsp; (and z gets set to "my")
canterbury_cs
canterbury_cs_0000110
Which of the following parts of a process&rsquo; memory is the largest?
[ "The code area", "The globals area", "The heap", "The stack" ]
C
Heap is the largest.
canterbury_cs
canterbury_cs_0000111
Prim&rsquo;s Algorithm is used to solve what problem?
[ "Finding the lowest parent of a heap", "Minimum spanning tree", "Shortest path in a graph from a source", "Sorting integers" ]
B
Prim's is used for MST.
canterbury_cs
canterbury_cs_0000112
Suppose you have a tree with a maximum depth of d and an average branching factor of b (i.e. each node has b children). You are searching for a particular node S located at depth m (m &lt;= d). You don't know where the node S is located, just that it is at depth m. What is an upper bound on the <em>space</em> complexity of breadth-first search (i.e. big-O notation) to find the node S starting from the root?
[ "O(d * b)", "O(b<sup>d</sup>)", "O(d<sup>b</sup>)", "O(b * m)" ]
B
In the worst case, we need to store all of the nodes, because the very last node we check at the maximum depth will be S.&nbsp; The deepest nodes of the graph will have O(b<sup>d</sup>) nodes, and in the worst case we would need to store all of these nodes. <img src="img/7.png" alt="" width="579" height="436">
canterbury_cs
canterbury_cs_0000113
Which of the following abstract datatypes would be the best choice for part of the implementation of the back button on a Web browser?
[ "a Stack&nbsp;", "a Queue", "a Priority Queue&nbsp;", "a List&nbsp;" ]
A
When you click on the back button, you should see the last page you visited, so the datatype that stores the previously visited webpages must be last-in-first-out. Of the abstract datatypes listed, Stack is the only one that is last-in-first-out.
canterbury_cs
canterbury_cs_0000114
Which of the following abstract datatypes would be the best choice for part of the implementation of&nbsp;a program modeling the arrival of patients to an emergency room in a hospital?
[ "a Stack", "a Queue", "A List", "a PriorityQueue" ]
D
In an emergency room, you want to serve patients in the order of how urgent their condition is, and if two patients have equally urgent conditions, in the order that they arrived. A PriorityQueue is the only abstract datatype listed that meets both of these conditions.&nbsp;
canterbury_cs
canterbury_cs_0000115
Two algorithms accomplish the same task on a collection of N items. Algorithm A performs N/2 operations. Algorithm B performs N log N operations. Under what conditions does algorithm A offer better performance?
[ "N &lt;= 4", "N &gt; 8", "N &gt; 2", "For all N." ]
D
For all legal collection sizes, N/2 &lt; N log N.
canterbury_cs
canterbury_cs_0000116
When is an adjacency matrix a good choice for implementing a graph?
[ "When the graph is undirected.", "When the graph is nearly complete.", "When a graph has few edges.", "When the graph contains no cycles." ]
B
The adjacency matrix will compactly and efficiently store edges when it contains little wasted space. In a complete graph, each vertex shares an edge with each other vertex, meaning all elements in the adjacency matrix will be used.
canterbury_cs
canterbury_cs_0000117
What is true about the pivot in quicksort?
[ "Before partitioning, it is always the smallest element in the list", "After partitioning, the pivot will always be in the centre of the list", "After partitioning, the pivot will never move again", "A random choice of pivot is always the optimal choice, regardless of input" ]
C
As the pivot will be to the right of all smaller elements and to the left of all larger elements, it is in the same position it will be when the array is sorted.
canterbury_cs
canterbury_cs_0000118
When is an adjacency list a good choice for implementing a graph?
[ "When the graph is undirected.", "When the graph is nearly complete.", "When a graph has few edges.", "When the graph contains no cycles." ]
C
With adjacency lists are used, each vertex stores its own list of vertices it's connected to. When a graph contains few edges, these lists will be very short and will likely consume less memory than the adjacency matrix.
canterbury_cs
canterbury_cs_0000119
You've got an algorithm that is O(N<sup>2</sup>). On the first run, you feed it a collection of size M. On the second run, you feed it a collection of size M / 2. Assuming each run has worst-case performance, how much time does the second run take?<span style="font-size: small;"><br></span>
[ "1/4 of the first", "1/2 of the first", "2/3 of the first", "3/4 of the first" ]
A
The first run took time proportional to M<sup>2</sup>. The second run took (M/2)<sup>2</sup>, or M<sup>2</sup>/4. The second run is 1/4 of the first.
canterbury_cs
canterbury_cs_0000120
Two algorithms accomplish the same task on a collection of N items. Algorithm A performs N<sup>2</sup> operations. Algorithm B performs 10N operations. Under what conditions does algorithm A offer better performance?
[ "N &lt; 10", "N &lt; 100", "N &gt; 10", "For all N." ]
A
The two algorithms offer equal performance when N = 10. For N greater than 10, N<sup>2</sup> &gt; 10N.
canterbury_cs
canterbury_cs_0000121
<pre lang="text/x-java">1. public BallPanel extends javax.swing.JPanel { 2. private Ball[] _balls; 3. public BallPanel(int numberOfBalls){ 4. ?????? 5. for (int i=0;i&lt;_balls.length;i++) 6. _balls[i] = new Ball(); 7. } 8. } </pre> &nbsp; We need to add something at line 4 above to avoid an error in line 5.&nbsp; Which of the following line 4 expressions fix the error in line 5?
[ "<code>super();</code>", "<code>_balls.setLength(numberOfBalls);</code>", "<code>_balls = new Ball[numberOfBalls];</code>", "&nbsp;<code>_balls.length = numberOfBalls;</code>" ]
C
The problem with line 5 (without adding line 4) is that _balls is declared, but not instantiated as an array, so _balls is null.&nbsp;&nbsp; The code compiles fine (assuming you have a class Ball that has a constructor with no parameters), but will crash at run time if you instantiate a BallPanel. B and D wouldn't help: B would crash at run time for the same reason as 5, and D gives a compile-time error since length is not directly settable for a Java array.&nbsp;&nbsp; A would work, but would have no effect on the problem.
canterbury_cs
canterbury_cs_0000122
Which of the following makes an appropriate pre-condition for this code?<br>double calculate_percentage(double sum, double n)<br><code>{</code> <pre lang="text/x-c"> // calculates and returns a percentage given a sum and a length (n) // &lt;missing pre-condition&gt; // POST: none return (sum / n) * 100; } </pre>
[ "PRE: sum &lt; 100", "PRE: n != 0", "PRE: sum != NULL and n != NULL", "PRE: none" ]
B
The code will faill if n = 0, as it will divide by 0.
canterbury_cs
canterbury_cs_0000123
Consider writing a program to be used by a farm to keep track of information about the fruits and vegetables they sell. For each sale, they would like to keep track of the type of item (eggplant, tomato, etc.), the quantity sold, the price, and the market at which the sale was made. Which of the following is the best way to represent the information?
[ "Define one class, <code>FarmSale</code>, with four fields: <code>type<span style=\"font-family: arial, helvetica, sans-serif;\">,</span></code> quantity<span style=\"font-family: arial, helvetica, sans-serif;\">, price<span style=\"font-family: arial, helvetica, sans-serif;\">, and market.</span></span>", "Define one superclass, <code>FarmSale</code>, with four subclasses: <code>Type</code>, <code>Quantity</code>, <code>Price</code>, and <code>Market</code>.", "Define five unrelated classes: <code>FarmSale</code>, <code>Type</code>, <code>Quantity</code>, <code>Price</code>, and <code>Market</code>.", "Define five classes: <code>FarmSale</code>, <code>Type</code>, <code>Quantity</code>, <code>Price</code>, and <code>Market</code>.. Make <code>Market</code> a subclass of <code>Price</code>, make <code>Price</code> a subclass of <code>Quantity</code>, make <code>Quantity</code> a subclass of <code>Type</code>, and make <code>Type</code> a subclass of <code>FarmSale</code>." ]
A
Which classes you define depends generally on the needs of the software. It might be good to have <code>Market</code> be a class of its own, with the address of the market, contact information for the organizers, etc. The item type might be modeled with a&nbsp;<code>Product</code>&nbsp;class, with information about the date it was planted, for example. But of the choices given, A is the best. We can rule out choices B, C, D, and E because price and quantity don't need data and associated methods of their own and are most appropriately modeled as fields in the <code>FarmSale</code> class. That leaves A.
canterbury_cs
canterbury_cs_0000124
Suppose you are writing a Java program to be used to manage information about the inventory in a store. The store&rsquo;s products include pagers, cell phones, and cameras. The cell phones are used for both communication and taking pictures, the pagers are only used for communication, and the cameras are used for taking pictures. Assume that a <code>Product</code> class has been defined. Which of the following is the best way to represent the remaining data?
[ "Define two subclasses of the <code>Product</code> class: <code>Communicator</code> and <code>PictureTaker</code>. Define two subclasses of the <code>Communicator</code> class: <code>Pager</code> and <code>CellPhone</code>; and define two subclasses of the <code>PictureTaker</code> class: <code>CellPhone</code> and <code>Camera</code>.", "Define three subclasses of the <code>Product</code> class: <code>Pager</code>, <code>CellPhone</code> and <code>Camera</code>. Also define two interfaces: <code>Communicator</code> and <code>PictureTaker</code>. Define the <code>Pager</code> and <code>CellPhone</code> classes to implement the <code>Communicator</code> interface, and define the <code>CellPhone</code> and <code>Camera</code> classes to implement the <code>PictureTaker</code> interface.", "Define five new classes, not related to the <code>Product</code> class: <code>Pager<span style=\"font-family: arial, helvetica, sans-serif;\">,</span></code> CellPhone<span style=\"font-family: arial, helvetica, sans-serif;\">, Camera<span style=\"font-family: arial, helvetica, sans-serif;\">, Communicator<span style=\"font-family: arial, helvetica, sans-serif;\">, and PictureTaker.</span></span></span>", "Define five subclasses of the <code>Product</code> class: <code>Pager<span style=\"font-family: arial, helvetica, sans-serif;\">,</span></code> CellPhone<span style=\"font-family: arial, helvetica, sans-serif;\">, Camera<span style=\"font-family: arial, helvetica, sans-serif;\">, Communicator<span style=\"font-family: arial, helvetica, sans-serif;\">, and PictureTaker.</span></span></span>" ]
B
Answer A is the easiest to rule out -- it gives&nbsp;<code>CellPhone</code> two superclasses, which is not permitted in Java. C is not the best choice because it doesn't capture the relationships among the various items. D captures some of the relationships but not all (for example, it's missing the relationship between <code>PictureTaker&nbsp;</code>and <code>Camera</code>). Answers B and E are very similar -- they focus on the question of which items should be modeled by interfaces and which by classes. B is a better choice for several reasons. Pagers, phones, and cameras all have both behaviors and data -- for example, the list of phone messages for a phone and the ability to take pictures for both phones and cameras -- while PictureTaker and Communicator correspond to behaviors. In addition, defining PictureTaker as an interface allows us to capture the fact that a cell phone is a product, a picture taker, *and* a communicator.&nbsp;
canterbury_cs
canterbury_cs_0000125
Consider the following short program, which does not meet all institutional coding standards: void vCodeString(char szText[ ]); /* First line */ #include &lt;stdio.h&gt; #include &lt;string.h&gt; #define MAX_LEN 12 int main(void) { &nbsp;&nbsp;&nbsp;&nbsp; char szData[MAX_LEN]; &nbsp;&nbsp;&nbsp;&nbsp; printf("Enter some text to code: "); &nbsp;&nbsp;&nbsp;&nbsp; scanf("%s", szData); &nbsp;&nbsp;&nbsp;&nbsp; vCodeString(szData); /* Line 8 */ &nbsp;&nbsp;&nbsp;&nbsp; printf("Coded string is %s\n", szData); } void vCodeString(char szText[ ]) { &nbsp;&nbsp;&nbsp;&nbsp; int i = -1; &nbsp;&nbsp;&nbsp;&nbsp; while(szText[++i]) &nbsp;&nbsp;&nbsp;&nbsp; { &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; szText[i] += (char)2; &nbsp;&nbsp;&nbsp;&nbsp; } } I would like to combine lines 8 and 9 into printf("Coded string is %s\n", vCodeString(szData)); Unfortunately, this gives me a syntax error. Why?
[ "&nbsp;printf can only match %s to a variable, not to a function.", "The parameter to vCodeString should be szText", "The parameter to vCodeString should be shown as szData[ ].", "vCodeString does not return a value." ]
D
The printf function cannot take as a parameter a function which does not return a value
canterbury_cs
canterbury_cs_0000126
The binary value 11011101 when coverted into a decimal value from two's complement notation is:
[ "-35", "35", "221", "-221" ]
A
Conversion of negative numbers in two's complement into decimal requires a bit flip, followed by the binary addition of 1. &nbsp;This value is then interpreted as an unsigned binary value.
canterbury_cs
canterbury_cs_0000127
Note draft only topics and explanation tba Consider the following short program: #include &lt;stdio.h&gt; void f1(void); int a; void main(void) { &nbsp;&nbsp;&nbsp;&nbsp; int b; &nbsp;&nbsp;&nbsp;&nbsp; a = b = 1; &nbsp;&nbsp;&nbsp;&nbsp; f1(); &nbsp;&nbsp;&nbsp;&nbsp; printf("%d %d", a, b); } void f1(void) { &nbsp;&nbsp;&nbsp;&nbsp; int b = 3; &nbsp;&nbsp;&nbsp;&nbsp; a = b; } The output from the print statement will be:
[ "1 1", "1 3", "3 1", "3 3" ]
C
Explanation to be completed
canterbury_cs
canterbury_cs_0000128
Finding the minimum value in a complete and&nbsp;balanced binary search tree is
[ "O(1)", "O(log N)", "O(N)", "O(N<sup>2</sup>)" ]
B
The minimum is the root's left-most descendent, which can be reached in log N steps.
canterbury_cs
canterbury_cs_0000129
An interface in Java can appropriately be used to model
[ "Abstract classes", "Unrelated classes that share particular capabilities", "Related classes that share particular attributes", "Classes that communicate using the same network protocol" ]
B
Interfaces allow us to specify common capabilities in unrelated classes: a way to say that two classes have the same methods without specifying the implementation (and allowing completely different implementations).&nbsp; For closely related classes (near each other in inheritance hierarchy) we can get common capabilities by having them in a common ancestor.&nbsp; Abstract classes provide a method to specify common capabilities via inheritance.&nbsp; Interfaces cannot be used to specify that two classes share a set of attributes (i.e. instance variables), which can be done by having classes inherit from a common ancestor with those attributes.
canterbury_cs
canterbury_cs_0000130
Suppose you are defining a Java&nbsp;<code>ProductItem</code> class to store information about the inventory in a store, and you want to give the class an instance variable for the number of those items currently in stock. Choose the best datatype for modeling this number:
[ "<code>double</code>", "<code>float</code>", "<code>int</code>", "a user-defined <code>NumberInStock</code> class" ]
C
A and B are wrong because you want to model an integer, not a floating point number. E is wrong because you probably want to use this number for adding and subtracting, not just for display.&nbsp; D is less good than C, because the built-in operations on ints will most likely be sufficient for the purposes of this variable.&nbsp;
canterbury_cs
canterbury_cs_0000131
Suppose you have a tree with a maximum depth of d and an average branching factor of b (i.e. each node has b children).&nbsp; You are searching for a particular node S located at depth m (m &lt;= d).&nbsp; You don't know where the node S is located, just that it is at depth m. What is an upper bound on the runtime complexity of breadth-first search (i.e. big-O notation) to find the node S starting from the root?
[ "O(d * b)", "O(b<sup>d</sup>)", "O(d<sup>b</sup>)", "O(b * m)" ]
B
In the worst-case, you would keep choosing sub-tree containing S last, and have to keep searching.&nbsp; Thus the worst-case is O(b<sup>d</sup>). The following picture may help: <img src="img/9.png" alt="" width="579" height="436">
canterbury_cs
canterbury_cs_0000132
What wil the following code print, assuming that N is a positive integer? <pre lang="text/x-java">int count=0; for (int i=0; i&lt;<strong>N</strong>; i++) { if (i % 2 == 0) { count++; } } System.out.println(count); </pre>
[ "N", "N/2", "N/2+1", "(N+1)/2" ]
D
If N is even, for example N=12, N/2 works.&nbsp; However, suppose N is odd, for example N=13.&nbsp; Here the result should be 7, which is (N+1)/2.&nbsp; However, for N=12, (N+1)/2 also works.&nbsp; (N+1)/2 works for all positive integer.
canterbury_cs
canterbury_cs_0000133
Two algorithms accomplish the same task on a collection of N items. Algorithm A performs (N/2)<sup>3</sup> operations. Algorithm B performs N<sup>2</sup> operations. Under what conditions does algorithm A offer strictly better performance?
[ "N &lt;= 7", "N &lt;= 8", "N &gt; 8", "For all N" ]
A
For N &lt;= 7, (N/2)<sup>3</sup> &lt; N<sup>2</sup>.
canterbury_cs
canterbury_cs_0000134
Identify the bug in the following Java code (if any): <br><code>public boolean search(T item,ListADT&lt;T&gt; list){ // 1</code> <pre lang="text/x-java"> if (list == null) // 2 return false; // 3 else if (list.first()==item) // 4 return true; // 5 else // 6 return this.search(item, list.rest()); // 7 } // 8 </pre>
[ "There is no base case", "The problem is not self-similar", "The problem does not get&nbsp;smaller", "There are no bugs" ]
D
For a recursive solution to a problem, you need three things:<br>(1) a base case (where the problem can be solved without recursion)<br>(2) a self-similar problem (one that contains similar problem(s) to itself)<br>(3) a way of making the problem smaller so you get closer to the base case Here (2) is satisfied -- lists contain smaller lists. (1) is satisfied by lines 2-5 of the method. And (3) is satisfied because line 7's recursive call takes the rest of the list as a parameter, rather than the whole list.
canterbury_cs
canterbury_cs_0000135
Suppose QueueADT is implemented using a singly linked list. What is the lowest Big-Oh time complexity that can be achieved for an enqueue&nbsp;method?:
[ "O(1)", "O(log<sub>2</sub> n)", "O(n)", "O(n<sup>2</sup>)" ]
A
If you keep a pointer to the last element of the queue, then the enqueue method just needs a fixed number of statements, which are the same independent of the size of the queue.&nbsp;
canterbury_cs
canterbury_cs_0000136
What terminates a failed linear probe in a full hashtable?
[ "A null entry", "Revisiting the original hash index", "A deleted node", "A node with a non-matching key" ]
B
A null entry will not appear in a full hashtable. Seeing the end of the array isn't correct, since we need to examine all elements, including those that appear before our original hash index. A node with a non-matching key is what started our probe in the first place. The purpose of leaving a deleted node in the table is so that probing may proceed past it.&nbsp;Revisiting the original hash index means we've looked at every entry and determined the item doesn't appear in the table.
canterbury_cs
canterbury_cs_0000137
Which of the following assertions is <em>incorrect</em>?
[ "A Python statement may return a value", "A Python expression may return a value", "A Python statement may produce a side effect", "A Python expression may produce a side effect" ]
A
Basically, a statement in Python is a special kind of function that doesn't return a value.&nbsp; Statements are things like <code>print</code> (in Python 2.x but not Python 3) and <code>import</code>. I think this is not a great question to put on a CS-1 exam beacuse it relies on terminology (statement, expression, side-effect) that doesn't really mean much until CS-2 or later.
canterbury_cs
canterbury_cs_0000138
What is<strong> not</strong> a property of a max-heap?
[ "It is complete", "A node&rsquo;s value is less than or equal to that of its parent", "Its values are sorted in when printed in level order", "Its root is the maximum element in the tree" ]
C
A max-heap need not be sorted.
canterbury_cs
canterbury_cs_0000139
Barack Obama wants to know the most efficient way to sort a million 32-bit integers. He knows it&rsquo;s not bubble sort. What is?
[ "Heapsort", "Insertion sort", "Mergesort", "Radix sort" ]
D
Radix sort will be O(n) and works nicely on integers; at such a large scale it will outperform the O(nlgn) sorting algorithms. (question is a reference to http://www.youtube.com/watch?v=k4RRi_ntQc8 )
canterbury_cs
canterbury_cs_0000140
Read the following method skeleton and choose the best expression to fill in the blank on <strong>line 2</strong> so that the method will behave correctly: <pre lang="text/x-java">/** * Takes a string reference and counts the number of times * the character 'A' or 'a' appears in the string object. * @param aString String reference to object containing chars. * @precondition aString is not null (you may assume this is true). * @return The number of times 'A' or 'a' appears in the string. */ public static int countAs(String aString) // line 1 { int counter = __________; // line 2 int totalA = 0; // line 3 while (counter &lt; __________) // line 4 { if ( __________.equals("A") ) // line 5 { totalA = totalA + __________; // line 6 } counter++; // line 7 } return __________; // line 8 } </pre>
[ "0", "1", "aString.size()", "aString.length" ]
A
This method must examine each character in the given string to see if it is 'A' or 'a', and uses a loop to do so. &nbsp;The variable <code>counter</code> is being used as a loop index, and by imagining what will fill in other blanks, is also being used to keep track of the position of the current character in the string that is being examined. &nbsp;Since line 7 methodically increases <code>counter</code> on each loop iteration, it must be traversing left-to-right through the string, so zero is the best choice for its initial value.
canterbury_cs
canterbury_cs_0000141
You are writing a depth-first search on a platform that doesn't support recursion. What data structure can help you complete your task?
[ "stack", "queue", "priority queue", "hashtable" ]
A
As you visit nodes, if you push their neighbors on a stack, the neighbors will be the first popped off when you need to backtrack. This behavior is what makes a depth-first search depth-first.
canterbury_cs
canterbury_cs_0000142
The worst-case time complexity of radix sort is:
[ "O(1)", "O(n)", "O(k n)", "O(n<sup>2</sup>)" ]
C
n is the number of items to be sorted, as usual, and k is the number of digits in the largest number in the list. Radix sort processes the entire list (n numbers) once for each of the k digits in the largest number in the list, so the work done is proportional to n*k.&nbsp;
canterbury_cs
canterbury_cs_0000143
A chained hash table has an array size of 512. What is&nbsp;the maximum number of entries that can be placed in&nbsp;the table?
[ "511", "512", "1024", "There is no maximum." ]
D
In a hashtable with chaining, each element is assigned to a particular cell in the array (a "bucket") using the hash function. Each bucket has a pointer to the start of a linked list, and the elements assigned to that bucket are stored in the linked list.&nbsp;
canterbury_cs
canterbury_cs_0000144
Read the following method skeleton and choose the best expression to fill in the blank on <strong>line 6</strong> so that the method will behave correctly: <pre lang="text/x-java">/** * Takes a string reference and counts the number of times * the character 'A' or 'a' appears in the string object. * @param aString String reference to object containing chars. * @precondition aString is not null (you may assume this is true). * @return The number of times 'A' or 'a' appears in the string. */ public static int countAs(String aString) // line 1 { int counter = __________; // line 2 int totalA = 0; // line 3 while (counter &lt; __________) // line 4 { if ( __________.equals("A") ) // line 5 { totalA = totalA + __________; // line 6 } counter++; // line 7 } return __________; // line 8 } </pre>
[ "0", "1", "<code>counter</code>", "<code>aString.length()</code>" ]
B
The variable <code>totalA</code> is being used as an accumulator to keep track of how many A's have been seen so far as the loop progresses. &nbsp;The if condition inside the loop is intended to detect whether the current character is an "A", and so the variable <code>totalA</code> should be incremented each time the condition is true. &nbsp;Therefore, the best answer for Line 6 is 1, so that <code>totalA</code> is incremented.
canterbury_cs
canterbury_cs_0000145
The following code for a method "minVal" contains a logic error on a single line in the method body, on one of the four lines indicated by comments:<br><br><code>public static int minVal(int[] y, int first, int last) {</code> <pre lang="text/x-java">/* This method returns the value of the minimum element in the * subsection of the array "y", starting at position * "first" and ending at position "last". */ int bestSoFar = y[first]; // line 1 for (int i=first+1; i&lt;=last; i++) { if ( y[i] &lt; y[bestSoFar] ) // line 2 </pre> <code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; bestSoFar = y[i];&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // line 3</code><br><br><code>&nbsp; } // for</code><br><br><code>&nbsp; return bestSoFar;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // line 4</code><br><br><code>} // method minVal</code><br><br><br>Which one of the four lines indicated by the comments contains the logic error?
[ "line 1", "line2", "line3", "line4" ]
B
line 2 should be<code> if ( y[i] &lt; bestSoFar )</code> <span style="font-family: arial,helvetica,sans-serif;">The other three lines use bestSoFar to remember the best VALUE seen thus far, whereas the buggy line is using bestSoFar as if bestSoFar contains the POSITION seen thus far.</span>
canterbury_cs
canterbury_cs_0000146
What is the size of the largest max-heap which is also a BST?
[ "2", "1", "4", "3" ]
A
You can have a left child of the root, but as soon as you add the right child, it falls apart.
canterbury_cs
canterbury_cs_0000147
The following code for a method "minVal" contains a logic error on a single line in the method body, on one of the four lines indicated by comments:<br><br><code>public static int minVal(int[] y, int first, int last) {</code> <pre lang="text/x-java">/* This method returns the value of the minimum element in the * subsection of the array "y", starting at position * "first" and ending at position "last". */ int bestSoFar = y[first]; // line 1 for (int i=first+1; i&lt;=last; i++) { if ( y[i] &lt; bestSoFar ) // line 2 </pre> <code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; bestSoFar = i;&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // line 3</code><br><br><code>&nbsp; } // for</code><br><br><code>&nbsp; return bestSoFar;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // line 4</code><br><br><code>} // method minVal</code><br><br>Which one of the four lines indicated by the comments contains the logic error?
[ "line 1", "line2", "line3", "line4" ]
C
line 3 should be <code>bestSoFar = y[i];</code> <code>The buggy code is remembering an array position, but the correct code remembers the value.</code>
canterbury_cs
canterbury_cs_0000148
How many objects and object reference would we have if the following code is executed? Student first_st = new Student(); Student second_st = new Student(); Student third_st = second_st;
[ "3, 2", "2, 3", "2, 2", "3, 3" ]
B
2, 2
canterbury_cs
canterbury_cs_0000149
Suppose you try to perform a binary search on the unsorted array {1, 4, 3, 7, 15, 9, 24}. How many of the items in this array will be found if they are searched for?
[ "3", "4", "5", "6" ]
C
7, 4, 9, 24, and 1 will be found if searched for. 15 and 3 will not, since they lie to the wrong side of a subrange's midpoint.
canterbury_cs
canterbury_cs_0000150
How many number will be printed if n = 5? public static void cSeries(int n) { &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.print(n + " "); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (n == 1) return; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (n % 2 == 0) cSeries(n / 2); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; else cSeries(3*n + 1); }
[ "3", "4", "5", "6" ]
D
5
canterbury_cs
canterbury_cs_0000151
For Club Scripting, to be a member a person must be aged 15 or older, but less than<br>50. What values would you use to boundary test a script designed to check if a<br>person was a suitable age to join?
[ "14, 15, 50, 51", "15, 16, 50, 51", "<br>15, 16, 49, 50", "<br>14, 15, 49, 50" ]
D
The boundary values are those at the boundary and those respectively one before and one past the boundary
canterbury_cs
canterbury_cs_0000152
Read the following method skeleton and choose the best expression to fill in the blank on <strong>line 5</strong>&nbsp;so that the method will behave correctly: <pre lang="text/x-java">/** * Takes a string reference and counts the number of times * the character 'A' or 'a' appears in the string object. * @param aString String reference to object containing chars. * @precondition aString is not null (you may assume this is true). * @return The number of times 'A' or 'a' appears in the string. */ public static int countAs(String aString) // line 1 { int counter = __________; // line 2 int totalA = 0; // line 3 while (counter &lt; __________) // line 4 { if ( __________.equals("A") ) // line 5 { totalA = totalA + __________; // line 6 } counter++; // line 7 } return __________; // line 8 } </pre>
[ "<code>aString.substring(counter).toUpperCase()</code>", "<code>aString.substring(counter)</code>", "<code>aString.substring(counter, counter + 1).toUpperCase()</code>", "<code>aString.charAt(counter).toUpperCase()</code>" ]
C
While both <code>charAt()</code> can be used to examine a single <code>char</code> in a string, <code>char</code> is a primitive type without any methods. &nbsp;Since the condition on Line 5 uses the <code>equals()</code> method to compare against another String value, the expression used to fill in the blank must produce a String object, so the <code>substring()</code> method is a better fit. &nbsp;The <code>substring()</code> method takes two parameters--a starting index and an ending index one past the end of the substring--and since the method counts both upper case and lower case A's, the result should be converted to upper case form before testing for equality against <code>"A"</code>. &nbsp;Thus, the best answer is <code>aString.substring(counter, counter + 1).toUpperCase()</code>.
canterbury_cs
canterbury_cs_0000153
You need to traverse a singly-linked list in reverse. What's the best worst-case performance you can achieve?
[ "O(1)", "O(log N)", "O(N)", "O(N log N)" ]
C
Iterate through the list in the forward direction, but prepend each node on a second list as you do. Then iterate through the second list, which will be in the desired reverse order and traversable in O(N) time.
canterbury_cs
canterbury_cs_0000154
Which data structure&nbsp;can be used to implement an abstract datatype&nbsp;such as the StackADT or QueueADT?
[ "an array", "a linked list", "both", "neither" ]
C
StackADT and QueueADT can both be implemented with either an array or a stack. Either may be the better choice, depending on the purpose of the program and the nature of the data being stored.&nbsp;
canterbury_cs
canterbury_cs_0000155
How many objects are created in the following declaration? String[] names = new String[10];
[ "0", "1", "10", "11" ]
B
None of the above
canterbury_cs
canterbury_cs_0000156
We say indexing is fast if it's done in O(1) time, searching is fast if done in O(lg N) time, and inserting and deleting are fast if done in O(1) time. Compared to other data structures, unsorted linked lists offer:
[ "slow indexing, slow search, slow insertions and deletions.", "fast indexing, fast search, slow insertions and deletions.", "fast indexing, slow search, slow insertions and deletions.", "slow indexing, slow search, fast insertions and deletions." ]
D
Linked lists do not support fast indexing. To get at element i, one must traverse the list i steps. Slow indexing makes for slow searching, as the binary search relies upon fast indexing to retrieve the middle element. Insertions and deletions, on the other hand, can be done in constant time, as only one or two neighboring links are affected.
canterbury_cs
canterbury_cs_0000157
Consider the following code snippet that copies elements (pixels) from one 2-d array (called pict), with maximum dimensions of maxWidth and maxHeight into another 2-d array called canvas. canvas = [][]<br>for row in range (0, maxHeight):<br>&nbsp; &nbsp; for col in range (0, maxWidth):<br>&nbsp; &nbsp; &nbsp; &nbsp; origPixel = pict[col][row]<br>&nbsp; &nbsp; &nbsp; &nbsp; canvas[width-1-col][row = origPixel If one were to display canvas, how would it compare to the orignal picture (as represented by pict)?
[ "Rotated 180 degrees around the vertical center line/column.", "Rotated 180 degrees around the horizontal center line/row.", "Rotated left 90 degrees.", "Rotated right 90 degrees." ]
A
Each pixel remains on the same row (line) that it originally was on. &nbsp;For any given row, the leftmost pixel swaps positions with the rightmost. &nbsp;The second pixel in a row swaps positions with the second last pixel in that row, etc. &nbsp;Hence, the picture is rotated across the vertical center line.
canterbury_cs
canterbury_cs_0000158
An example of something that could be built using&nbsp;a QueueADT is a structure that models:
[ "The undo operation in a word processor", "the back button in a web browser", "the customers waiting to talk to an online&nbsp;helpdesk", "a hundred names in alphabetical order, where&nbsp;names are added and removed frequently" ]
C
Choices A and B are applications where when you delete, you need to delete the item that was added most recently (a LIFO structure). This is not possible in a queue, where you always delete the item that was added *first*. Choice D is an application where you need to be able to delete from the beginning, middle, or end of the structure, something that is also impossible in a queue.&nbsp; Choice E is an application where a element (an intersection) could be connected to several other elements. This is also impossible in a queue. Choice C is the only one where it makes sense to retrieve the elements in the order in which they arrived.&nbsp;
canterbury_cs
canterbury_cs_0000159
This sorting algorithm splits the collection into two halves, sorts the two halves independently, and combines the results.
[ "bubble sort", "insertion sort", "quick sort", "merge sort" ]
D
Merge sort splits the collection, sorts the two halves, and merges them.
canterbury_cs
canterbury_cs_0000160
Locating a new node's insertion point in a binary search tree stops when
[ "We reach a null child.", "We find a node greater than the node to be inserted.", "We reach the tree's maximum level.", "We find a node lesser than the node to be inserted." ]
A
Finding nodes less than or greater than the new node happens frequently as we traverse the tree. Tree's don't have maximum levels. The insertion point isn't necessarily a leaf node. The remaining option of stopping when we reach null is the correct answer because we have found the new node's parent node.
canterbury_cs
canterbury_cs_0000161
What are hash functions<strong> not</strong> used for? (Or at least, should not be used for.)
[ "Storing values in hash tables", "Checking file integrity", "Encrypting passwords", "Digital signatures on files" ]
C
Hash functions should be used to store passwords, but not to encrypt them!
canterbury_cs
canterbury_cs_0000162
How many objects are created in the following declaration? <code>String name;</code>
[ "0", "1", "This declaration causes a run-time error", "It is not legal to write this declaration in Java" ]
A
It is not legal to write this declaration in Java
canterbury_cs
canterbury_cs_0000163
Nathan is on the run (apparently the US is about to invade Canada). He needs to grab food.<br>Each piece of food around him has a nutritional value, and a weight. He wants to put the<br>most calories in his backpack, but it can only hold up to certain weight. What should he<br>optimize for when deciding which foods to bring?
[ "The value of food", "The value / weight ratio of food", "The weight / value ratio of food", "The weight of food" ]
B
Greedy approach to fractional knapsack.
canterbury_cs
canterbury_cs_0000164
Suppose you are defining a Java <code>ProductItem</code> class to store information about the inventory in a store, and you want to give the class an instance variable for the price of that item. Which of the following is the best datatype for the instance variable that models the price?
[ "<code>String</code>", "<code>float</code>", "<code>int</code>", "a user-defined <code>Money</code> class" ]
D
Arguments can be made for any of these choices (except perhaps "int"). I would give <code>Money</code> an edge, because a user-defined class allows you to write methods to display the value properly, do arithmetic on it, and perhaps convert it to different currencies. But I'm going to tag this as a question with more than one answer.&nbsp;
canterbury_cs
canterbury_cs_0000165
<pre lang="text/x-java">1.public class FirstApp extends wheels.users.Frame { 2. private wheels.users.Ellipse _ellipse; 3. 4. public FirstApp() { 5. _ellipse = new wheels.users.Ellipse(); 6. } 7. 8. public static void main(String[] args) { 9. FirstApp app = new FirstApp(); 10. } 11.} </pre> &nbsp; What does line 2 accomplish (cause to happen)?
[ "<code>wheels.users.Ellipse</code> is given <code>_ellipse</code> as an alias", "An invisible <code>Ellipse</code> is drawn on the screen", "<code>_ellipse</code> is declared as a <code>wheels.users.Ellipse</code>", "<code>wheels.users.Ellipse</code> is set to be a <code>private</code> object" ]
C
Remember that in Java we need to declare variables, and then instantiate them (using new).&nbsp; Line 2 is simply a declaration -- the variable gets instantiated (in line 5) when a FirstApp gets instantiated.
canterbury_cs
canterbury_cs_0000166
We say indexing is fast if it's done in O(1) time, searching is fast if done in O(lg N) time, and inserting and deleting are fast if done in O(1) time.&nbsp;Compared to other data structures, unsorted arrays offer:
[ "slow indexing, slow search, slow insertions and deletions.", "fast indexing, fast search, slow insertions and deletions.", "fast indexing, slow search, slow insertions and deletions.", "slow indexing, slow search, fast insertions and deletions." ]
C
Unsorted arrays can be indexed in constant time (which is fast), searched in O(N) time (which is not as good as O(lg N)), and restructured in O(N) time (which is not as good as O(1) time).
canterbury_cs
canterbury_cs_0000167
One of the things in Java that allows us to use polymorphism is that the declared type and actual type of a variable may be different. In Java, the actual type of a parameter or variable&rsquo;s value can be any concrete class that is
[ "the same as the declared type, or any subclass of the declared type (if the declared type is a class)", "any class that <code>implements</code> the declared type (if the declared type is an interface)", "any subclass of a class that <code>implements</code> the declared type (if the declared type is an interface)", "A, B, and C above." ]
D
The rule of thumb is that the declared type is the same or more abstract than the actual type.&nbsp; If the declared type is a class, the things that are equally or less abstract are its descendants -- a subclass specializes a class.&nbsp; If declared type is an interface, it is an abstraction of any class that implements it, or by the relationship between classes and its descendants, any class that is a subclass of something that implements it. Java wants a guarantee that the actual type will have the declared type's methods.&nbsp; That can be via inheritance or implementing an interface, or a combination of the two.
canterbury_cs
canterbury_cs_0000168
An example of something that could be implemented using&nbsp;a Stack is:
[ "The undo operation in Word", "The back button in a web browser", "A postfix calculator", "All of the above" ]
D
Anytime you're solving a problem where you're adding and removing data and you always need to remove the item that was added most recently is suited to a Stack. This is called a last-in-first-out property, or LIFO. Back buttons, the undo operation, and postfix calculators all have the last-in-first-out property.&nbsp;
canterbury_cs
canterbury_cs_0000169
Suppose you are writing software for a helpdesk. Each request is entered into the system as it arrives.&nbsp; Which of the following abstract datatypes would be the best choice to ensure that the requests are handled in exactly the same order in which they arrive?
[ "A Stack", "A Queue", "A List", "A PriorityQueue" ]
B
A Queue is the only abstract datatype where elements are removed in exactly the same order that they arrived in.&nbsp;
canterbury_cs
canterbury_cs_0000170
If an inorder traversal of a complete binary tree visits the nodes in the order ABCDEF (where each letter is the value of a node), which order are the nodes visited during an postorder traversal?
[ "ACBEFD", "DBACFE", "DEBFCA", "DBFACE" ]
A
DBACFE
canterbury_cs
canterbury_cs_0000171
What is not true about a binary search tree?
[ "It is a binary tree", "It is a perfect tree", "The leftmost node is the smallest node in the tree", "When printed with inorder traversal, it will be sorted" ]
B
BSTs need not be perfect.
canterbury_cs
canterbury_cs_0000172
Suppose you are trying to choose between an array and a singly linked list to store the data in your Java program. Which arguments would correctly support one side or the other?
[ "Linked lists are better suited to a program where the amount of data can change unpredictably.&nbsp;", "Arrays provide more efficient access to individual elements.&nbsp;", "Linked lists provide more efficient access to individual elements.&nbsp;", "A and B only" ]
D
Array elements can be accessed in constant time, but access to an element of a linked list is O(n), so B is correct and C is incorrect. A is also correct, because arrays require you to guess how much memory will be needed and set aside a fixed amount, while linked lists use memory as needed for the data that are being stored. Since A and B are correct and C is not, the answer is D.
canterbury_cs
canterbury_cs_0000173
The insertion sort operates by maintaining a sorted list. When a new element is added, we traverse the list sequentially until will find the new element's appropriate location. Suppose instead that the new location was found using a binary search instead of a sequential search. What is the complexity of this new binary insertion sort?
[ "O(log N)", "O(N<sup>2</sup>)", "O(N + log N)", "O(N * log N)" ]
B
The binary search will indeed speed up finding the location of the newly added object. However, we still have the problem of shifting all subsequent elements. This algorithm, like the regular insertion sort, is O(N<sup>2</sup>).
canterbury_cs
canterbury_cs_0000174
For the binary search algorithm implemented on a sorted list stored in an array, what is its running time?
[ "O(1)", "O(log<sub>2&nbsp;</sub>n)", "O(n)", "O(n log<sub>2</sub> n)" ]
B
Binary search repeately "throws away" half of the list still under investigation when looking for a given value in the list. &nbsp;Hence the run time of the algorithm is the number of times a values can be divided in two, until one reaches the value 1: O(log<sub>2</sub> n)
canterbury_cs
canterbury_cs_0000175
Suppose we're modeling a person with just name and age. The notation {"Javier", 31} refers to a 31-year-old named Javier. Now, suppose we have this collection of five people: {"Lupe", 29} {"Dean", 29} {"Lars", 28} {"Javier", 31} {"Di", 28} Which of the following ordered collections is the result of applying a <em>stable</em> sort to this collection, where the sorting criteria orders by age?
[ "{\"Javier\", 31}<br>{\"Dean\", 29}<br>{\"Lupe\", 29}<br>{\"Di\", 28}<br>{\"Lars\", 28}", "{\"Javier\", 31}<br>{\"Lupe\", 29}<br>{\"Dean\", 29}<br>{\"Lars\", 28}<br>{\"Di\", 28}", "{\"Lars\", 28}<br>{\"Di\", 28} \n {\"Dean\", 29} \n {\"Lupe\", 29}<br>{\"Javier\", 31}", "{\"Lars\", 28}<br>{\"Di\", 28}<br>{\"Dean\", 29} \n {\"Lupe\", 29}<br>{\"Javier\", 31}" ]
B
A stable sort preserves the relative order of elements with the same keys. Thus, Lupe must appear before Dean and Lars must appear before Di. Only the correct answer maintains this order.
canterbury_cs
canterbury_cs_0000176
Which data structure&nbsp;provides direct access to elements using indexes?
[ "an array", "a linked list", "both", "neither" ]
A
If you declare an array in languages that have them, such as Pascal, C, C++, Java, etc., you can access an element of the array by giving the index of the value to be retrieved.&nbsp;
canterbury_cs
canterbury_cs_0000177
The <code>StackADT</code>'s&nbsp;<code>pop</code> operation:
[ "adds a new item at the bottom of the Stack", "returns without removing the top item on the&nbsp;Stack", "removes and returns the top item on the Stack", "adds a new item at the top of the Stack" ]
C
"pop" is the traditional term for removing an element from a stack. By definition, the element removed from a stack is always the one that was added most recently, or the one at the "top."
canterbury_cs
canterbury_cs_0000178
The dequeue operation:
[ "&nbsp;adds a new item at the front of a queue", "returns without removing the item at the front of a queue", "removes and returns the item at the front of a queue", "adds a new item at the end of a queue" ]
C
dequeue is the name for the operation that removes an element from a queue. Specifically, it removes the item that was added *first* (just as the first person in a line gets served first).&nbsp;
canterbury_cs
canterbury_cs_0000179
What does this function do? void iFunction(char sz[]) { &nbsp;&nbsp;&nbsp;&nbsp; int iLen = 0; &nbsp;&nbsp;&nbsp;&nbsp; while ( sz[iLen]) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; sz[iLen++] = '-'; }
[ "Copies a string", "Finds and returns a character in a string", "Replaces all letters in a string with - characters", "Finds the length of a string" ]
C
The Function iterates through the array to the end, replacing each character with the "-" character
canterbury_cs
canterbury_cs_0000180
What will be printed? public static void main(String [] args){ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int[] array = {1, 2, 3, 4, 1, 2, 3, 4}; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; System.out.print( specialSum(array, 3)); } public static int specialSum (int[] integerArray , int index){ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int sum = index % 2 ==0 ? integerArray [index]*2 : integerArray [index] +1; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if( index == 0) return sum; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return sum + specialSum(integerArray, index-1); }
[ "16", "32", "15", "30" ]
A
15
canterbury_cs
canterbury_cs_0000181
What is output by the code shown in the question below. Think aboutit carefully - it may be a bit tricky! void main(void) { &nbsp;&nbsp;&nbsp;&nbsp; static int aiTable[10] = {0,1,2,3,4,5,6,7,8,9}; &nbsp;&nbsp;&nbsp;&nbsp; int i; &nbsp;&nbsp;&nbsp;&nbsp; for(i = 0; i &lt; 10; i++) &nbsp;&nbsp;&nbsp;&nbsp; { &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if( !(aiTable[i] % 2)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; printf("%d", aiTable[i]); &nbsp;&nbsp;&nbsp;&nbsp; } }
[ "02468", "13579", "01234", "56789" ]
A
Modulus is the remainder of integer division of two numbers with the result placed somewhere. The modulus function of a and b, a being the dividend and b being the divisor, is a - int(a/b) * b. For example, using integer results... 47/4 = 11<br>47%4 = 3 Check it: 47 = 11*4 + 3 Source http://wiki.answers.com/Q/What_is_the_difference_between_division_and_modulus_in_%27C%27_language In this case the negatively phrased line of code "if( !(aiTable[i] % 2))" is an alternative way of&nbsp; expressing the more common phrasing of a modulus arithmetic expression as given below If you wanted to know if a number was odd or even, you could use modulus to quickly tell you by asking for the remainder of the number when divided by 2. #include &lt;iostream&gt; using namespace std; int main() { &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int num; &nbsp;&nbsp;&nbsp;&nbsp; cin &gt;&gt; num; &nbsp;&nbsp;&nbsp;&nbsp; // num % 2 computes the remainder when num is divided by 2 &nbsp;&nbsp;&nbsp;&nbsp; if ( num % 2 == 0 ) &nbsp;&nbsp;&nbsp;&nbsp; { &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; cout &lt;&lt; num &lt;&lt; " is even "; &nbsp;&nbsp;&nbsp;&nbsp; } return 0; } The key line is the one that performs the modulus operation: "num % 2 == 0". A number is even if and only if it is divisible by two, and a number is divisible by another only if there is no remainder. source: http://www.cprogramming.com/tutorial/modulus.html
canterbury_cs
canterbury_cs_0000182
In Java, which of the following is not considered to be part of the signature of a method?
[ "Return type", "Method name", "Number of parameters", "Types and order of parameters" ]
A
In Java the return type is not considered as part of the signature.&nbsp; Why should I care?&nbsp; If i want to use method overloading (have different methods with the same name) the methods must have unique signatures, and so i cannot have 2 methods with the same name that have the same number, type, and order of parameters that differ on return type.
canterbury_cs
canterbury_cs_0000183
Given the code <pre lang="text/x-java">int x = 27; int y = 12; </pre> &nbsp; What is the value of the expression <code>x%y</code>?
[ "2", "2.25", "3", "3.0" ]
C
In Java, the % operator means "remainder." So this question is asking, "What is the remainder when you divide 27 by 12?" &nbsp; 27 - (2*12) = 3, so the answer is 3.
canterbury_cs
canterbury_cs_0000184
Given the code <pre lang="text/x-java">int x = 27; int y = 12; </pre> &nbsp; What is the value of the expression &nbsp;<code>x/y</code>?
[ "2", "2.25", "3", "3.0" ]
A
In Java, when we divide one int value by another, we get another integer. You can start by doing the usual division (which would give you 2.25 in this case) and then remove the decimal part.&nbsp;
canterbury_cs
canterbury_cs_0000185
Suppose you have a binary search tree with no right children. Furthermore, key A is considered greater than key B if A.compareTo(B) &gt;= 0. Which of the following explains how this tree may have ended up this way?
[ "The root value was the minimum.", "All keys were identical.", "It was filled in descending order.", "The tree is a preorder tree." ]
C
If the greatest node was inserted first, with each successive node having a lesser key than its predecessor, we'd end up with all left children. Adding nodes with identical keys produces right children.
canterbury_cs
canterbury_cs_0000186
What is the logic error in the following implementation of sequential search? 1 &nbsp;def sequentialSearch(listOfValues):<br>2 &nbsp; &nbsp; &nbsp; target = input("value searching for: ")<br>3 &nbsp; &nbsp; &nbsp; listSize = len(listOfValues)<br>4 &nbsp; &nbsp; &nbsp; targetFound = False<br>5 &nbsp; &nbsp; &nbsp; targetLocation = 0<br>6 &nbsp; &nbsp; &nbsp; current = 0<br>7 &nbsp; &nbsp; &nbsp; while (current &lt; listSize):<br>8 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (listOfValues[current] == target):<br>9 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; targetFound = True<br>10 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; targetLocation = current 11 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;else: 12 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; targetFound = False<br>13 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;current = current + 1 <br>14 &nbsp; &nbsp; &nbsp;if targetFound:<br>15 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print "the target was found at location: ", targetLocation<br>16 &nbsp; &nbsp; &nbsp;else:<br>17 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;print "target was not found"
[ "Line 10", "Line 7", "Lines 11-12", "Line 8" ]
C
The else clause resets&nbsp;<em>targetFound</em> if a match is ever found. &nbsp;Hence, in effect, with this else clause present, only the test with the last element in the list is "remembered."
canterbury_cs
canterbury_cs_0000187
Which of the following lines of code will correctly read in the integer value foo?
[ "scanf(\"%d\", &amp;foo);", "scanf(\"%f\", foo);", "scanf(\"%f\", &amp;foo);", "scanf(\"%f\\n\", foo);" ]
A
(A) is the correct answer; %d is used for reading in integers. The \n in (D) is unnecessary. Finally, scanf requires a pointer to a variable's address -- hence the ampersand.
canterbury_cs
canterbury_cs_0000188
A printer is shared among several computers in a network. Which data structure is proper to keep the sent prints in order to provide service in turn?
[ "Queue", "Stack", "Single Linked List", "one dimensional array" ]
A
Single Linked List
canterbury_cs
canterbury_cs_0000189
Java virtual machine handles a chain of method calls. Which data structure is proper for this purpose?
[ "Queue", "Stack", "single linked list", "one dimensional array" ]
B
single linked list
canterbury_cs
canterbury_cs_0000190
Removing a node from a heap is
[ "O(1)", "O(log N)", "O(N)", "O(N log N)" ]
B
The last node is moved into the empty spot, which may be the root, and it may trickle back down to the bottom level. The performance is based on the number of levels in the tree. As heaps are balanced, the performance is O(log N).
canterbury_cs
canterbury_cs_0000191
We need to keep track of the changes that a user makes when working with a word processor. Which data structure is more proper for this purpose?
[ "Queue", "Stack", "Single Linked List", "one dimensional array" ]
B
Single Linked List
canterbury_cs
canterbury_cs_0000192
Suppose you have a list of numbers stored in consecutive locations in a Java array. What is the worst-case time complexity of finding a given element in the array using linear search?
[ "O(1)", "O(log n)", "O(n)", "O(n log n)" ]
C
Linear search is O(n).
canterbury_cs
canterbury_cs_0000193
Which data structure has a better performance when customer offers needs to be stored/restored for an auction?
[ "An array", "A single linked list", "A priority queue", "A tree" ]
C
A priority queue
canterbury_cs
canterbury_cs_0000194
Noor writes a program in C to evulate some Taylor series, to help her with her calculus homework. She remembers to<code> #include&lt;math.h&gt;</code> before calling the<code> pow</code> function. But when she compiles with <code>gcc taylor.c</code>, she gets an error that <code>pow</code> is undefined. What she should instead type in the command-line to compile successfully?
[ "gcc taylor.c -01", "gcc taylor.c -lm", "gcc taylor.c -math", "gcc taylor.c -o taylor" ]
B
-lm will manually link the math library.
canterbury_cs
canterbury_cs_0000195
<pre lang="text/x-java">public int factorial (int n) { if (n == 0) return 1; else if (n &gt; 0) return n * factorial(n - 1); else return -1; // invalid input } </pre> <br><span style="font-family: arial, helvetica, sans-serif;">The Big-Oh time complexity of this method is:</span>
[ "O(1)", "O(log n)", "O(n)", "O(n<sup>2</sup>)" ]
C
The factorial method will be called n times, so the time complexity is proportional to n.
canterbury_cs
canterbury_cs_0000196
Assuming "FRED" is an ASCII text file which opens correctly, what will be displayed by this code? #define MAX 128 FILE *pFile = fopen("FRED", "r"); unsigned uCount = 0; while(!feof(pFile)) { &nbsp;&nbsp;&nbsp;&nbsp; char ch; &nbsp;&nbsp;&nbsp;&nbsp; ch = fgetc(pFile); &nbsp;&nbsp;&nbsp;&nbsp; uCount++; } printf("%u", uCount);
[ "The number of characters in the file", "The number of words in the file", "The number of sentences in the file", "The number of lines of text in the file" ]
A
The function reads the file character by character and increments a counter on each read, the result of which is printed on reaching the end of file giving the total character count in the file
canterbury_cs
canterbury_cs_0000197
An array has been declared as shown then used to store the data in the table below. int iTable[3][5]; /* Declaration */ 27 32 14&nbsp;&nbsp; 9 26 74 42 30 15 19 41 63 48 20&nbsp; 3 What is the value of iTable [3] [4]?
[ "B", "20", "&nbsp;iTable[3][4] does not exist", "19" ]
C
The index values for the array start from 0 so iTable [3] [4] refers to the 4th row and the 5th column, where the 4th row does not exist for additional explanation cf. http://www.tutorialspoint.com/cprogramming/c_multi_dimensional_arrays.htm
canterbury_cs
canterbury_cs_0000198
Which of the following is a list of Java class names that are both syntactically legal and obey the standard naming convention?
[ "R2D2, Chameleon, public", "R2D2, Chameleon, Iguana", "r2d2, chameleon, public", "R2D2, Iguana, _hello" ]
B
Choice (b) is correct, because all of the names start with an uppercase letter, followed by 0 or more letters, numbers, and/or underscores.&nbsp;
canterbury_cs
canterbury_cs_0000199
When we use recursion to solve a problem, we have <ol> <li>a problem that contains one or more problems that are similar to itself</li> <li>a version of the problem that is simple enough to be solved by itself, without recursion, and</li> <li>a way of making the the problem simpler so that it is closer to (and ultimately the same as) the version in 2.</li> </ol> What is 2. called?
[ "The simple case", "The inductive case", "The base case", "The iterative case" ]
C
Base case is the term we use for the case that is simple enough to solve directly.&nbsp;&nbsp; We probably lifted the term from induction proofs in Mathematics, which is fitting.