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_0000400
|
Which of the following is an equivalent boolean expression for:
<strong>NOT(A AND B)</strong>
|
[
"<strong>(NOT A) AND (NOT B)</strong>",
"<strong>A OR B</strong>",
"<strong>(NOT A) AND B</strong>",
"<strong>(NOT A) OR (NOT B)</strong>"
] |
D
|
When applying DeMorgan's law, one distributes the <strong>NOT </strong>over both operands and then one exchanges<strong> AND</strong>'s for <strong>OR</strong>'s, or <strong>OR</strong>'s for <strong>AND</strong>'s
|
canterbury_cs
|
canterbury_cs_0000401
|
The following method, called maxRow(), is intended to take one parameter: a List where the elements are Lists of Integer objects. You can think of this parameter as a matrix--a list of rows, where each row is a list of "cells" (plain integers). The method sums up the integers in each row (each inner list), and returns the index (row number) of the row with the largest row sum. Choose the best choice to fill in the blank on <strong>Line 6</strong> so that this method works as intended:
<pre lang="text/x-java">public static int maxRow(List<List<Integer>> matrix)
{
int maxVec = -1; // Line 1
int maxSum = Integer.MIN_VALUE; // Line 2
for (int row = 0; row < __________; row++) // Line 3
{
int sum = 0; // Line 4
for (int col = 0; col < __________; col++) // Line 5
{
sum = sum + __________; // Line 6
}
if (___________) // Line 7
{
maxSum = __________; // Line 8
maxVec = __________; // Line 9
}
}
return maxVec; // Line 10
}
</pre>
|
[
"<code>maxSum</code>",
"<code>matrix[row][col]</code>",
"<code>matrix.get(row).get(col)</code>",
"<code>matrix.get(col).size()</code>"
] |
C
|
The loop on Line 5 incrementally accumulates the sum of all entries in the current row, which is held in the local variable <code>sum</code>. The purpose of Line 6 is to add the current column value to this running sum. The value of the current cell in the matrix is <code>matrix.get(row).get(col)</code>.
|
canterbury_cs
|
canterbury_cs_0000402
|
The<em> lifetime</em> of a parameter in Java is
|
[
"Really long",
"From when its method is called until it returns",
"From when you define the method until you quit out of Eclipse",
"As long as the program is running"
] |
B
|
The lifetime of a variable is the duration over which it keeps a value unless you change it. With a parameter, its value is set when you invoke the method, and it retains that value (or what every you subsequently set it to) until you return.
|
canterbury_cs
|
canterbury_cs_0000403
|
Rohan has the code<code> int len = strlen("Rohan")</code>. What is the value of <code>len</code>?
|
[
"0",
"5",
"6",
"8"
] |
B
|
While the \0 will be added to the end of the array, it is not included in the length calculation.
|
canterbury_cs
|
canterbury_cs_0000404
|
Suppose <code>s</code> is an instance of a stack that can store Strings, and I execute the following statements?
<pre lang="text/x-java">1. s.push("Finland");
2. s.push("is");
3. s.push("my");
4. String w = s.peek();
5. String x = s.pop();
6. s.push("home");
7. String y = s.pop();
8. String z = s.pop();
</pre>
What is the value of z after executing these statements in order?
|
[
"\"Finland\"",
"\"is\"",
"\"my\"",
"\"home\""
] |
B
|
After the three pushes the stack contents (from top) is ["my" "is" "Finland" ...]
4. doesn't change the stack.
the contents of the stack are (after each numbered instruction)
5. ["is" "Finland" ...]
6. ["home" "is" "Finland" ...]
7. ["is" "Finland" ...]
8. sets z to "is", which is popped, leaving the stack as ["Finland" ...]
So B is correct.
|
canterbury_cs
|
canterbury_cs_0000405
|
<pre lang="text/x-java"> public class Outer extends SomeClass implements SomeInterface{
...
private class Inner extends AnotherClass {
????
}
}
</pre>
Suppose I define an inner class, as is abstractly illustrated by the code above. Assuming that I do not shadow anything (by declaring or defining something in the inner class with the same name as something accessible in the outer class), what in the outer class is accessible to the code in the inner class (at ????, e.g.) ?
|
[
"All protected methods and protected instance variables of the outer class",
"All public methods and public instance variables of the outer class",
"All methods and all public instance variables of the outer class",
"All methods and instance variables of the outer class."
] |
D
|
The inner class is within the scope of the outer class, which means that all instance variables and public methods (including methods inherited from the outer class's ancestors). are accessible from the inner class.
Shadowing is a problem, since there is no automatic way to refer to the instance of the outer class.
|
canterbury_cs
|
canterbury_cs_0000406
|
<pre lang="text/x-java">1. public BallPanel extends javax.swing.Panel {
2. private Ball[] _balls;
3. public BallPanel(int numberOfBalls){
4. _balls = new Ball[numberOfBalls];
5. for (int i=0;i<_balls.length;i++)
6. _balls[i] = new Ball();
7. }
8. }
</pre>
<span style="font-family: arial,helvetica,sans-serif;">In the above Java code, what is the value of <code>_balls.length</code> immediately after lines 4 and 6 (respectively)?</span>
|
[
"<code>0, numberOfBalls</code>",
"<code>numberOfBalls, numberOfBalls</code>",
"<code>i, numberOfBalls</code>",
"<code>0, numberOfBalls – 1</code>"
] |
B
|
When the array is instantiated in line 4, its length is set (to numberOfBalls). Lines 5 and 6 set the values of the array elements, but do not change the length of the array.
|
canterbury_cs
|
canterbury_cs_0000407
|
<pre lang="text/x-java">1. import java.util.ArrayList;
2. public BallPanel extends javax.swing.JPanel {
3. private ArrayList <Ball> _moreBalls;
4. public BallPanel(int numberOfBalls){
5. _moreBalls = new ArrayList<Ball>();
6. for (int i=0;i<numberOfBalls;i++)
7. _moreBalls.add(new Ball());
8. }
9. }
</pre>
What is the value of _moreBalls.size() immediately after lines 4 and 6 (respectively) if we invoke the BallPanel constructor?
|
[
"<code>0, numberOfBalls</code>",
"<code>numberOfBalls, numberOfBalls</code>",
"<code>i, numberOfBalls</code>",
"<code>0, numberOfBalls – 1</code>"
] |
A
|
A is correct. When you instantiate an ArrayList (in line 4) its size (the number of elements in the ArrayList) is zero because you haven't added any elements; lines 5 and 6 add numberOfBalls elements to the ArrayList, so after that the size is numberOfBalls.
|
canterbury_cs
|
canterbury_cs_0000408
|
Suppose <code>s</code> is an instance of a stack that can store Strings, and I execute the following statements starting with <code>s</code> empty:
<pre lang="text/x-java">1. s.push("Iceland");
2. s.push("is");
3. String w = s.peek();
4. String x = s.pop();
5. s.push("cool");
6. String y = s.pop();
7. boolean z = s.isEmpty();
</pre>
What is the value of z after executing this sequence of expressions?
|
[
"<code>\"Iceland\"</code>",
"<code>\"cool\"</code>",
"<code>true</code>",
"<code>false</code>"
] |
D
|
In the sequence of operations, we pushed 3 things onto the stack, and only popped 2 off (and at no point had we popped more times than we pushed). So the stack is not empty.
|
canterbury_cs
|
canterbury_cs_0000409
|
Kun has a method:
<pre lang="text/x-c">struct node{
struct node *next;
int val;
}
</pre>
<br><code>void delete_root(struct node *root)</code>
<pre lang="text/x-c">{
free(root);
root = NULL;
}
</pre>
What is most likely to happen?
|
[
"Deletes a copy of root",
"Deletes root",
"Segfault",
"A lot of crazy stuff will be printed"
] |
D
|
The code frees memory it shouldn't be, and will do a core dump.
|
canterbury_cs
|
canterbury_cs_0000410
|
One of the key features of Object-oriented programming is encapsulation.
Because of encapsulation, we generally have _________ instance variables and _____________ methods.
|
[
"protected, private",
"private, public",
"public, private",
"public, public"
] |
B
|
Encapsulation involves hiding the internal state of an object, in particular not allowing direct access to an object's instance variables. We use methods to define the interactions other objects can have with an object, so the internal structure and information is not revealed to the outside.
|
canterbury_cs
|
canterbury_cs_0000411
|
Assume that an object of the following class has just been created:
<pre lang="text/x-java">public class Unknown
{
private int x;
public Unknown()
{
x = 17;
method1();
method2(5);
method3();
System.out.println(x); // Line D
}
public void method1()
{
--x;
int x = this.x;
x++;
System.out.println(this.x); // Line A
}
public void method2(int x)
{
x++;
System.out.println(x); // Line B
}
public void method3()
{
--x;
int x = 2;
x++;
System.out.println(x); // Line C
}
}
</pre>
What output is produced by <strong>Line A</strong> when an instance of this class is created?
|
[
"2",
"3",
"16",
"17"
] |
C
|
Line A prints the value of the field called <code>x</code>. That field is initialized to 17 in the constructor, and then decremented on the first line of <code>method1()</code>, so the value printed is 16. The increment operation in <code>method1()</code> applies to the local variable within the method, not the field that happens to have the same name.
|
canterbury_cs
|
canterbury_cs_0000412
|
Consider the following method:
<pre lang="text/x-java">public int size() {
XXXXXX
}
</pre>
Which of the following could replace the XXXXX and be the body of the <code>size()</code> method for a Queue that uses a circular array implementation?
|
[
"<pre lang=\"text/x-java\">if (front==rear)\n return 0;\nreturn rear-front;\n</pre>",
"<pre lang=\"text/x-java\">if (rear>front)\n return rear-front;\nreturn front-rear;\n</pre>",
"<pre lang=\"text/x-java\">if (front==0 && front==rear) \n return 0;\nif (front>rear) \n return front-rear;\nreturn rear-front;\n</pre>",
"<pre lang=\"text/x-java\">if (front>rear) \n return front-rear;\nif (front==rear) \n return 0;\nreturn rear-front;\n</pre>"
] |
B
|
B, C, D all work.
E would be correct, but it won't compile since it doesn't return a value on <em>all</em> paths.
|
canterbury_cs
|
canterbury_cs_0000413
|
Assume that an object of the following class has just been created:
<pre lang="text/x-java">public class Unknown
{
private int x;
public Unknown()
{
x = 17;
method1();
method2(5);
method3();
System.out.println(x); // Line D
}
public void method1()
{
--x;
int x = this.x;
x++;
System.out.println(this.x); // Line A
}
public void method2(int x)
{
x++;
System.out.println(x); // Line B
}
public void method3()
{
--x;
int x = 2;
x++;
System.out.println(x); // Line C
}
}
</pre>
What output is produced by <strong>Line B</strong> when an instance of this class is created?
|
[
"3",
"5",
"6",
"17"
] |
C
|
Line B prints the value of the parameter called <code>x<span style="font-family: arial, helvetica, sans-serif;"> in <code>method2()</code></span></code>. That parameter is given the value 5 when <code>method2()</code> is called from the constructor, and then the parameter itself is incremented on the first line of <code>method2()</code>, so the value printed is 6.
|
canterbury_cs
|
canterbury_cs_0000414
|
Consider the following implementation of a contains() method for a Queue in Java:
<pre lang="text/x-java">public class Queue<E> {
private LinkedList<E> list;
// Assume correct enqueue(),
// dequeue(), size() methods
public boolean contains(E e){
for (int i=0; i<list.size(); i++) {
if (list.get(i).equals(e)) {
return true;
}
}
return false;
}
}
</pre>
What is the runtime (big-Oh) complexity of this method?
|
[
"O(1)",
"O(n)",
"O(n*log<sub>2</sub>n)",
"O(n<sup>2</sup>)"
] |
D
|
This is sort of a trick question. The get() method of a LinkedList is O(n), and we are calling this method O(n) times, so we have O(n<sup>2</sup>).
|
canterbury_cs
|
canterbury_cs_0000415
|
Assume that an object of the following class has just been created:
<pre lang="text/x-java">public class Unknown
{
private int x;
public Unknown()
{
x = 17;
method1();
method2(5);
method3();
System.out.println(x); // Line D
}
public void method1()
{
--x;
int x = this.x;
x++;
System.out.println(this.x); // Line A
}
public void method2(int x)
{
x++;
System.out.println(x); // Line B
}
public void method3()
{
--x;
int x = 2;
x++;
System.out.println(x); // Line C
}
}
</pre>
What output is produced by <strong>Line C</strong> when an instance of this class is created?
|
[
"2",
"3",
"15",
"16"
] |
B
|
Line C prints the value of the local variable called <code>x</code> declared in <code>method3()</code>. That variable is initialized to 2 in its declaration, and then incremented on the following line of <code>method3()</code>, so the value printed is 3.
|
canterbury_cs
|
canterbury_cs_0000416
|
<pre lang="text/x-java">int a = 1;
int d = 7;
if (b > c)
{
a = 2;
}
else
{
d = a * 2;
}
</pre>
Which of the following code fragments is equivalent to the version above? "Equivalent" means that both fragments would assign the same values to <code>a</code> and <code>d</code>, given the same values for <code>b</code> and <code>c</code>.
|
[
"<pre lang=\"text/x-java\">int a = 1;\nint d = 7;\nif (b < c)\n{\n d = a * 2;\n}\nelse\n{\n a = 2;\n}\n</pre>",
"<pre lang=\"text/x-java\">int a = 1;\nint d = 7;\nif (b <= c)\n{\n d = a * 2;\n}\nelse\n{\n a = 2;\n}\n</pre>",
"<pre lang=\"text/x-java\">int a = 1;\nint d = 7;\nif (b >= c)\n{\n a = 2;\n}\nelse\n{\n d = a * 2;\n} \n</pre>",
"<pre lang=\"text/x-java\">int a = 1;\nint d = 7;\nif (b > c)\n{\n d = a * 2;\n}\nelse\n{\n a = 2;\n}\n</pre>"
] |
B
|
The opposite condition of <code>(b > c)</code> is <code>(b <= c)</code>. The correct answer has this opposite if test, and the two actions in the branches of the if statement in opposite positions.
|
canterbury_cs
|
canterbury_cs_0000417
|
Which command will tell gcc to optimize recursion so that any code that has been executed will not be executed again? (e.g. fibo(3) will only be calculated once.)
|
[
"gcc fibonacci.c -03",
"gcc fibonacci.c -o",
"gcc fibonacci.c --optimize",
"gcc fibonacci.c -g"
] |
A
|
Optimization level 3 is what is needed to avoid redundant recursive calls.
|
canterbury_cs
|
canterbury_cs_0000418
|
Malik is using quicksort. He has the list [3, 4, 5, 1, 0] and will be pivoting around the element 3. After partitioning, what will the list look like?
|
[
"[3, 4, 5, 0, 1]",
"[1, 0, 3, 4, 5]",
"[3, 1, 0, 4, 5]",
"[0, 1, 3, 4, 5]"
] |
B
|
In the implementation of quicksort we used in class, all elements before the pivot are moved before the pivot; all elements after the pivot are moved after it.
|
canterbury_cs
|
canterbury_cs_0000419
|
What output will the following code fragment produce?
<pre lang="text/x-java">public void fn()
{
int grade = 91;
int level = -1;
if (grade >= 90)
if (level <= -2)
System.out.println("A-level");
else
System.out.println("B-status");
}
</pre>
|
[
"A-level",
"B-status",
"\"A-level\"",
"\"B-status\""
] |
B
|
Despite the indentation, no braces appear around the body of either if statement's branch(es). As a result, the else is associated with the second (inner) if. Since the outer if statement's condition is true, but the inner if statement's condition is false, the output is <code>B-status</code>.
|
canterbury_cs
|
canterbury_cs_0000420
|
Suppose you want to write a Python function that takes a list as a parameter and returns True if there are no instances of 3 immediately followed by a 4, and False otherwise.
So this list returns True: [ 3 5 4 ]
But this list returns false: [ 1 2 3 4 5 ].
The following code has a bug in it. Which line contains the bug?
<pre lang="text/x-python">def no34(nums):
for i in range(len(nums)): #line1
if nums[i]==3 and nums[i+1]==4: #line2
return False #line3
return True #line4
</pre>
|
[
"line1",
"line2",
"line3",
"line4"
] |
A
|
This will go over the edge of the list! Line1 should be:
<code>for i in range(len(nums)<strong>-1</strong>):</code>
|
canterbury_cs
|
canterbury_cs_0000421
|
Suppose you want to write a Python function that takes a list as a parameter and returns true if there are <em>no</em> instances of 3 immediately followed by a 4, and false otherwise. So this list returns True: [ 3 5 4 ] But this list returns false: [ 1 2 3 4 5 ].
<pre lang="text/x-python">def no34(nums):
for i in range(len(nums)-1):
if nums[i]==3 and nums[i+1]==4:
return False #line1
else:
return True #line2
return False #line3
</pre>
What changes, if any, should be made to make this code correct
|
[
"No changes are necessary; it is correct as written",
"switch line1 and line2 (i.e return True for line1 and return False for line 2)",
"delete line2 (take the else statement with it)",
"switch line1 and line2 (i.e return True for line1 and return False for line 2) \n and \n delete line2 (take the else statement with it)"
] |
C
|
The else clause should be removed. If we don't see a 3-4, we can't conclude anything about the rest of the list.
|
canterbury_cs
|
canterbury_cs_0000422
|
Assume that an object of the following class has just been created:
<pre lang="text/x-java">public class Unknown
{
private int x;
public Unknown()
{
x = 17;
method1();
method2(5);
method3();
System.out.println(x); // Line D
}
public void method1()
{
--x;
int x = this.x;
x++;
System.out.println(this.x); // Line A
}
public void method2(int x)
{
x++;
System.out.println(x); // Line B
}
public void method3()
{
--x;
int x = 2;
x++;
System.out.println(x); // Line C
}
}
</pre>
What output is produced by <strong>Line D</strong> when an instance of this class is created?
|
[
"2",
"3",
"15",
"16"
] |
C
|
Line D prints the value of the field called <code>x</code>. That field is initialized to 17 in the constructor, and then decremented on the first line of <code>method1()</code>, and decremented again on the first line of <code>method3()</code>, so by the time execution reaches the <code>println()</code> method call at the end of the constructor, the value printed is 15.
|
canterbury_cs
|
canterbury_cs_0000423
|
Consider the following partial and incomplete <code>SpellChecker</code> class that uses an <code>ArrayList</code> to hold a reference list of correctly-spelled words:
<pre lang="text/x-java">public class SpellChecker
{
private List<String> dictionary; // spelling storage. // Line 1
// assume a constructor exists that correctly instantiates and
// populates the list (i.e. loads the dictionary for the spellchecker)
public boolean spelledCorrectly(String word) // Line 2
{
for (int counter = 0; counter < __________; counter++) // Line 3
{
if (word.equals(__________)) // Line 4
{
return true; // Line 5
}
}
return false; // Line 6
}
public void addWord(String word) // Line 7
{
if (__________) // check word is NOT already in the dictionary // Line 8
{
__________; // add word at end of the dictionary // Line 9
}
}
// other SpellChecker class methods would follow
}
</pre>
<br><span style="font-family: arial, helvetica, sans-serif;">Choose the best choice to fill in the blank on line 4 so that the code operates correctly.</span>
|
[
"<code>dictionary.find(word)</code>",
"<code>dictionary[counter]</code>",
"<code>dictionary[word]</code>",
"<code>dictionary.get(counter)</code>"
] |
D
|
The loop in <code>spelledCorrectly()</code> checks each word in the list called <code>dictionary</code> for the specified word, using <code>counter</code> to traverse through all positions in the list. To retrieve a single word at the given position, use the expression <code>dictionary.get(counter)</code>.
|
canterbury_cs
|
canterbury_cs_0000424
|
The following class definitions illustrates which important object-oriented programming concept?
class Animal:<br> def __init__(self, name): # Constructor of the class<br> self.name = name<br> def talk(self): # Abstract method, defined by convention only<br> raise NotImplementedError("Subclass must implement abstract method")
class Cat(Animal):<br> def talk(self):<br> return 'Meow!'
class Dog(Animal):<br> def talk(self):<br> return 'Woof! Woof!'
|
[
"Polymorphism",
"Inheritance",
"Responsibility driven design",
"Tight/strong cohesion and loose coupling"
] |
A
|
This is the classic example of polymorphism. Consider the following code:
animals = [Cat('Missy'), Dog('Lassie')]
for animal in animals:<br> print(animal.name + ': ' + animal.talk())
# prints the following:<br># Missy: Meow!<br># Lassie: Woof! Woof!
|
canterbury_cs
|
canterbury_cs_0000425
|
Which of the following is the best definition of an algorithm?
|
[
"A well-ordered collection of unambiguous and effectively computable operations that when executed produces a result and halts in a reasonably short amount of time.",
"A well-ordered collection of unambiguous and effectively computable operations that when executed produces a result and halts in a finite amount of time.",
"A collection of unambiguous and effectively computable operations that when executed produces a result and halts in a finite amount of time.",
"A well-ordered collection of unambiguous and effectively computable operations that when executed produces a result."
] |
B
|
Option B provides the best definition. A key component is that in order to be an algorithm, it must eventually halt.
|
canterbury_cs
|
canterbury_cs_0000426
|
Consider the code:<br><code>strcpy(str1, "abc");</code>
<code>strcat(str1, "def");</code> <br>What is the value of str1?
|
[
"abc",
"def",
"abcdef",
"defabc"
] |
C
|
def is concatenated onto the end of abc
|
canterbury_cs
|
canterbury_cs_0000427
|
Gianluca wants to sort the array array, which has a length of length. He writes the following C code to do this. Which sorting algorithm has he implemented?
<br><code>void sort_array(int *array, int length)</code>
<pre lang="text/x-c">{
int max, i, temp;
while(length > 0)
{
max = 0;
for(i = 1; i < length; i++)
if(array[i] > array[max])
max = i;
temp = array[length-1];
array[length-1] = array[max];
array[max] = temp;
length--;
}
}
</pre>
|
[
"Insertion sort",
"Selection sort",
"Bubble sort",
"Mergesort"
] |
B
|
Students should take note that this code is looking for the max elements over and over again.
|
canterbury_cs
|
canterbury_cs_0000428
|
The worst-case time complexity of insertion sort is:
|
[
"O(1)",
"O(n)",
"O(n log n)",
"O(n<sup>2</sup>)"
] |
D
|
Consider the case where the data are in reverse order. You will need to compare element 2 with element 1 and swap them; then compare element 3 with elements 1 and 2, shift elements 1 and 2 over, and insert element 3 in the first position, and so on. Each element will be compared with all of the elements before it, resulting in a total of n(n-1)/2 comparisons.
|
canterbury_cs
|
canterbury_cs_0000429
|
Bryon has dynamically allocated memory for an array named arr using malloc. Once he’s<br>done using arr in his program, what single line of code should he write to free the block of<br>memory that arr points to?
|
[
"free(arr);",
"free(*arr);",
"free(&arr);",
"dealloc(arr);"
] |
A
|
it's free(arr)
|
canterbury_cs
|
canterbury_cs_0000430
|
Which of the following makes an appropriate pre-condition for this code?
<pre lang="text/x-c">double calculate_percentage(double sum, double n)
{
// calculates and returns a percentage given a sum and a length (n)
// <missing pre-condition>
// POST: none
return (sum / n) * 100;
}
</pre>
|
[
"PRE: sum < 100",
"PRE: n != 0",
"PRE: sum != NULL and n != NULL",
"PRE: none"
] |
B
|
Want to avoid the divide by 0
|
canterbury_cs
|
canterbury_cs_0000431
|
Junyoung runs the program after compiling with <code>gcc print random number.c -Wall</code>:
<br><code>#include<stdlib.h></code>
<pre lang="text/x-c">int main()
{
int x = rand();
printf("%d\n", x);
}
</pre>
<br>What is <strong>not</strong> true about it?
|
[
"GCC will give a warning since stdio.h was not included",
"GCC will give a warning since <code>main</code> does not return an <code>int</code>",
"It will print a different number every time",
"It will only need four bytes of stack space"
] |
C
|
Rand was not seeded.
|
canterbury_cs
|
canterbury_cs_0000432
|
Fill in the incomplete line of code so this recursively prints the contents of the array <code>arr</code>:
<br><code>void print_array(int *arr, int length)</code>
<pre lang="text/x-c">{
if(length > 0)
{
printf("%d\n", *arr);
</pre>
<code> print_array(arr + 1, <strong>____________ </strong></code><code>);</code>
<pre lang="text/x-c"> }
}
</pre>
|
[
"print_array(arr + 1, 0);",
"print_array(arr + 1, length - 1);",
"print_array(arr + 1, ++length);",
"print_array(arr + 1, length);"
] |
B
|
Note the base case requires the length to be decreasing.
|
canterbury_cs
|
canterbury_cs_0000433
|
Consider the following partial and incomplete <code>SpellChecker</code> class that uses an <code>ArrayList</code> to hold a reference list of correctly-spelled words:
<pre lang="text/x-java">public class SpellChecker
{
private List<String> dictionary; // spelling storage. // Line 1
// assume a constructor exists that correctly instantiates and
// populates the list (i.e. loads the dictionary for the spellchecker)
public boolean spelledCorrectly(String word) // Line 2
{
for (int counter = 0; counter < __________; counter++) // Line 3
{
if (word.equals(__________)) // Line 4
{
return true; // Line 5
}
}
return false; // Line 6
}
public void addWord(String word) // Line 7
{
if (__________) // check word is NOT already in the dictionary // Line 8
{
__________; // add word at end of the dictionary // Line 9
}
}
// other SpellChecker class methods would follow
}
</pre>
<br><span style="font-family: arial, helvetica, sans-serif;">Choose the best choice to fill in the blank on line 9 so that the code operates correctly.</span>
|
[
"<code>dictionary.set(word)</code>",
"<code>dictionary.put(counter, word)</code>",
"<code>dictionary.set(dictionary.length, word)</code>",
"<code>dictionary.add(word)</code>"
] |
D
|
Use the <code>add()</code> method to add a new value to the end of a <code>List</code>.
|
canterbury_cs
|
canterbury_cs_0000434
|
Seray is hashing the values 6, 96, 33, 77 into a hash table of size 10. 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)"
] |
C
|
A collides on 9/96; B does not collide; C collides on 6/33; D collides on 33/77.
|
canterbury_cs
|
canterbury_cs_0000435
|
What does <code>atoi("hello")</code> return?
|
[
"0",
"-1",
"hello",
"e"
] |
A
|
it wil be 0
|
canterbury_cs
|
canterbury_cs_0000436
|
In a hashtable that uses separate chaining to handle collisions, what, if any, restrictions should be placed on the table size?
|
[
"Any number is fine, as the linear probing is guaranteed to find an element.",
"Any number is fine, since probing is irrelevant.",
"It should be a prime number, to ensure that in probing we will test each node.",
"It should be an odd number, to ensure that there's always a middle element."
] |
B
|
With separate chaining, no probing is done. Each entry in the table is a linked list, and all items with the hash index appear in the list.
|
canterbury_cs
|
canterbury_cs_0000437
|
The <strong>Fibonacci sequence</strong> is 0, 1, 1, 2, 3, 5, 8, 13 ... Any term (value) of the sequence that follows the first two terms (0 and 1) is equal to the sum of the preceding two terms. Consider the following incomplete method to compute any term of the Fibonacci sequence:
<pre lang="text/x-java">public static int fibonacci(int term)
{
int fib1 = 0; // Line 1
int fib2 = 1; // Line 2
int fibn = 0; // Line 3
if (term == 1) // Line 4
{
return fib1; // Line 5
}
if (term == 2) // Line 6
{
return fib2; // Line 7
}
for (__________) // Line 8: loop to the nth term
{
fibn = __________; // Line 9: compute the next term
fib1 = __________; // Line 10: reset the second preceding term
fib2 = __________; // Line 11: reset the immediate preceding term
}
return fibn; // Line 12: return the computed term
}
<span style="font-family: arial, helvetica, sans-serif;">Choose the best answer to fill in the blank on line 9.
</span></pre>
|
[
"<code>fib2 - fib1</code>",
"<code>fib1 + fibn</code>",
"<code>fibn + fib2</code>",
"<code>fib1 + fib2</code>"
] |
D
|
As described in the first part of the question, each term in the sequence is the sum of the previous two terms, so <code>fibn = fib1 + fib2</code>.
|
canterbury_cs
|
canterbury_cs_0000438
|
Which of the following is most appropriate as the missing post-condition?
<br><code>void move_north_east(int *x, int *y)</code>
<pre lang="text/x-c">{
// Moves a robot north-east in our coordinate system
// by one step north and one step east
// PRE: x != NULL, y != NULL
// <missing post-condition>
(*x)++;
(*y)++;
}
</pre>
|
[
"POST: x != NULL, y != NULL",
"POST: x is incremented; y is incremented",
"POST: x’s pointee is incremented; y’s pointee is incremented",
"POST: none"
] |
C
|
what x to points to is being updated, not x itself
|
canterbury_cs
|
canterbury_cs_0000439
|
The <strong>Fibonacci sequence</strong> is 0, 1, 1, 2, 3, 5, 8, 13 ... Any term (value) of the sequence that follows the first two terms (0 and 1) is equal to the sum of the preceding two terms. Consider the following incomplete method to compute any term of the Fibonacci sequence:
<pre lang="text/x-java">public static int fibonacci(int term)
{
int fib1 = 0; // Line 1
int fib2 = 1; // Line 2
int fibn = 0; // Line 3
if (term == 1) // Line 4
{
return fib1; // Line 5
}
if (term == 2) // Line 6
{
return fib2; // Line 7
}
for (__________) // Line 8: loop to the nth term
{
fibn = __________; // Line 9: compute the next term
fib1 = __________; // Line 10: reset the second preceding term
fib2 = __________; // Line 11: reset the immediate preceding term
}
return fibn; // Line 12: return the computed term
}
</pre>
<span style="font-family: arial, helvetica, sans-serif;">Choose the best answer to fill in the blank on line 10.</span>
<span style="font-family: arial, helvetica, sans-serif;"> </span>
|
[
"<code>fib1</code>",
"<code>fib2</code>",
"<code>fibn</code>",
"<code>fib1 + fib2</code>"
] |
B
|
Since each term in the sequence is formed by adding together the previous two terms, the local variables <code>fib1</code> and <code>fib2</code> are used to store the previous two terms for recall in computing the next value in the sequence. After computing the next term in the sequence, the loop moves the value of <code>fib2</code> into <code>fib1</code>, and the value of <code>fibn</code> into <code>fib2</code>, so that the previous two terms are ready for use in the next loop iteration.
|
canterbury_cs
|
canterbury_cs_0000440
|
Dhruv has some recursive code that contains the base case <code>if(left > right)</code>
<br>Which algorithm is he <em>most</em> likely to be implementing?
|
[
"heapsort",
"insertion sort",
"quicksort",
"Fibonacci"
] |
C
|
Only quicksort is usually implemented with such a base case.
|
canterbury_cs
|
canterbury_cs_0000441
|
The <strong>Fibonacci sequence</strong> is 0, 1, 1, 2, 3, 5, 8, 13 ... Any term (value) of the sequence that follows the first two terms (0 and 1) is equal to the sum of the preceding two terms. Consider the following incomplete method to compute any term of the Fibonacci sequence:
<pre lang="text/x-java">public static int fibonacci(int term)
{
int fib1 = 0; // Line 1
int fib2 = 1; // Line 2
int fibn = 0; // Line 3
if (term == 1) // Line 4
{
return fib1; // Line 5
}
if (term == 2) // Line 6
{
return fib2; // Line 7
}
for (__________) // Line 8: loop to the nth term
{
fibn = __________; // Line 9: compute the next term
fib1 = __________; // Line 10: reset the second preceding term
fib2 = __________; // Line 11: reset the immediate preceding term
}
return fibn; // Line 12: return the computed term
}
</pre>
<span style="font-family: arial, helvetica, sans-serif;">Choose the best answer to fill in the blank on line 11.</span>
|
[
"<code>fib1</code>",
"<code>fib2</code>",
"<code>fibn</code>",
"<code>fib1 + fib2</code>"
] |
C
|
Since each term in the sequence is formed by adding together the previous two terms, the local variables <code>fib1</code> and <code>fib2</code> are used to store the previous two terms for recall in computing the next value in the sequence. After computing the next term in the sequence, the loop moves the value of <code>fib2</code> into <code>fib1</code>, and the value of <code>fibn</code> into <code>fib2</code>, so that the previous two terms are ready for use in the next loop iteration.
|
canterbury_cs
|
canterbury_cs_0000442
|
Polymorphism is used when different classes we are modeling can do the same thing (i.e. respond to the same method calls), and we don't know which class an object will be at compile time. In Java, this can be implemented using either inheritance or interfaces.
Choose the best reason below for choosing inheritance polymorphism
|
[
"There is no defined interface that works for all of the classes that I want to allow",
"The classes are closely related in the inheritance hierarchy;",
"The classes are in the same containment hierarchy",
"It is the kind of polymorphism that I understand the best"
] |
B
|
If the classes are closely related in the inheritance hierarchy it should be possible to have the shared methods in some common superclass, which is close.
|
canterbury_cs
|
canterbury_cs_0000443
|
<span style="font-family: arial, helvetica, sans-serif;">Given the following Java code:</span>
<pre lang="text/x-java">if (x >= 0) {
System.out.println("1");
} else if (x < 20) {
System.out.println("2");
} else {
System.out.println("3");
}
System.out.println("4");
</pre>
<span style="font-family: arial, helvetica, sans-serif;">For what integer values of <code>x</code> will 1 be among the values printed?</span>
|
[
"x < 0",
"x >= 0",
"x >= 20",
"All values of x"
] |
B
|
The first branch of the conditional statement will print "1" for any x value greater than or equal to 0.
|
canterbury_cs
|
canterbury_cs_0000444
|
You are looking for a method getSequence(int n, char c) that returns a String of n characters c. Which of the following will not meet your needs?
|
[
"<pre lang=\"text/x-java\">String getSequence(int n, char c) {\n String s = \"\";\n for (int i = 0; i < n; ++i) {\n s = s + c;\n }\n return s;\n}\n</pre>",
"<pre lang=\"text/x-java\">String getSequence(int n, char c) {\n String s = \"\";\n while (n > 0) {\n s += c;\n }\n return s;\n}\n</pre>",
"<pre lang=\"text/x-java\">String getSequence(int n, char c) {\n return n * c;\n}\n</pre>",
"<pre lang=\"text/x-java\">String getSequence(int n, char c) {\n String s = \"\";\n for (int i = 1; i <= n; ++i) {\n s += c;\n }\n return s;\n}\n</pre>"
] |
C
|
A char multiplied by an int produces an int, not a String. Example C doesn't even compile.
|
canterbury_cs
|
canterbury_cs_0000445
|
<pre lang="text/x-java">public class RecursiveMath
...
public int fib (int a) {
if (a < 2)
return a;
else
return fib(a-1) + fib(a-2);
}
...
}
</pre>
Given the above definition, what is the result of executing the following?
<pre lang="text/x-java">RecursiveMath bill = new RecursiveMath();
int x = bill.fib(-1);
</pre>
|
[
"x is set to -1",
"x is set to undefined",
"The code does not terminate",
"The code cannot be executed, because it won't compile"
] |
A
|
Since fib is called with parameter of -1, a gets bound to -1. Since a < 2, the method returns the value of a, -1.
|
canterbury_cs
|
canterbury_cs_0000446
|
<pre lang="text/x-java">public class RecursiveMath
...
public int fib (int a) {
if (a < 2)
return a;
else
return fib(a-1) + fib(a-2);
}
...
}
</pre>
What is the base case for <code>fib</code> in the above definition?
|
[
"a",
"<code>fib(a-1) + fib(a-2);</code>",
"<code>fib(a)</code> for <code>a < 2</code>",
"<code>fib(a)</code> for <code>a ≥ 2</code>"
] |
C
|
The base case is the version of the problem that can be solved directly, i.e. without a recursive call.
|
canterbury_cs
|
canterbury_cs_0000447
|
What is the difference between
<br><code>struct node* linked_list_node = malloc(sizeof(struct node));</code>
<pre lang="text/x-c">linked_list_node->val = 3;
linked_list_node->next = NULL;
</pre>
and:
<br><code>struct node linked_list_node;</code>
<pre lang="text/x-c">linked_list_node.val = 3;
linked_list_node.next = NULL;
</pre>
<span style="font-family: arial,helvetica,sans-serif;">?</span>
|
[
"The first needs more memory than the second",
"The first’s node is stored on the heap; the second’s is stored on the stack",
"The second is globally-accessible in the program; the first is locally accessible",
"There is no difference"
] |
B
|
Dynamic alloc goes on heap; static goes on stack.
|
canterbury_cs
|
canterbury_cs_0000448
|
Consider the code
<br><code>struct capacitor{</code>
<pre lang="text/x-c"> double capacitance;
};
</pre>
If given the variable struct capacitor *cap, which of the following will NOT print the address of cap’s capacitance?
|
[
"printf(\"%p\\n\", cap )",
"printf(\"%p\\n\", &(cap.capacitance) )",
"printf(\"%p\\n\", &((*cap).capacitance) )",
"printf(\"%p\\n\", &(cap->capacitance) )"
] |
B
|
C and D are equivalent; A is equivalent to them as capacitance is the first thing stored in the struct.
|
canterbury_cs
|
canterbury_cs_0000449
|
Consider the following partial and incomplete <code>SpellChecker</code> class that uses an <code>ArrayList</code> to hold a reference list of correctly-spelled words:
<pre lang="text/x-java">public class SpellChecker
{
private List<String> dictionary; // spelling storage. // Line 1
// assume a constructor exists that correctly instantiates and
// populates the list (i.e. loads the dictionary for the spellchecker)
public boolean spelledCorrectly(String word) // Line 2
{
for (int counter = 0; counter < __________; counter++) // Line 3
{
if (word.equals(__________)) // Line 4
{
return true; // Line 5
}
}
return false; // Line 6
}
public void addWord(String word) // Line 7
{
if (__________) // check word is NOT already in the dictionary // Line 8
{
__________; // add word at end of the dictionary // Line 9
}
}
// other SpellChecker class methods would follow
}
</pre>
<br><span style="font-family: arial, helvetica, sans-serif;">Choose the best choice to fill in the blank on line 3 so that the code operates correctly.</span>
|
[
"<code>dictionary.size()</code>",
"<code>dictionary.length()</code>",
"<code>dictionary.size</code>",
"<code>dictionary.length</code>"
] |
A
|
The loop in <code>spelledCorrectly()</code> checks each word in the list called <code>dictionary</code> for the specified word, so the upper limit on the loop counter should be <code>dictionary.size()</code>. Remember that lists provide a <code>size()</code> method to retrieve the number of entries (the <code>length()</code> method is used for strings, and <code>length</code> as a field access is used for arrays).
|
canterbury_cs
|
canterbury_cs_0000450
|
Consider the following partial and incomplete <code>SpellChecker</code> class that uses an <code>ArrayList</code> to hold a reference list of correctly-spelled words:
<pre lang="text/x-java">public class SpellChecker
{
private List<String> dictionary; // spelling storage. // Line 1
// assume a constructor exists that correctly instantiates and
// populates the list (i.e. loads the dictionary for the spellchecker)
public boolean spelledCorrectly(String word) // Line 2
{
for (int counter = 0; counter < __________; counter++) // Line 3
{
if (word.equals(__________)) // Line 4
{
return true; // Line 5
}
}
return false; // Line 6
}
public void addWord(String word) // Line 7
{
if (__________) // check word is NOT already in the dictionary // Line 8
{
__________; // add word at end of the dictionary // Line 9
}
}
// other SpellChecker class methods would follow
}
</pre>
<br><span style="font-family: arial, helvetica, sans-serif;">Choose the best choice to fill in the blank on line 8 so that the code operates correctly.</span>
|
[
"<code>!dictionary.contains(word)</code>",
"<code>!dictionary.find(word)</code>",
"<code>dictionary[word] == null</code>",
"<code>dictionary.get(word)</code>"
] |
A
|
To check whether a given value is present in a <code>List</code>, use the <code>contains()</code> method.
|
canterbury_cs
|
canterbury_cs_0000451
|
<pre lang="text/x-java">1. public BallPanel extends javax.swing.JPanel {
2. private Ball[] _balls;
3. public BallPanel(int numberOfBalls){
4. _balls = new Ball[numberOfBalls];
5. for (int i=0;i<_balls.length;i++)
6. _balls[i] = new Ball();
7. }
8. public void ballCopy () {
9. Ball[] temp = new Ball[2 * _balls.length];
10. for (int j=0; j< _balls.length; j++0)
11. _temp[j] = _balls[j];
12. _balls = temp;
13. }
13. ...
</pre>
After executing
<pre lang="text/x-java">BallPanel myPanel = new BallPanel(10);
_myPanel.ballCopy();
</pre>
Which of the following is true?
|
[
"The array <code>_balls</code> is unchanged in myPanel",
"The elements of <code>temp</code> are copies of the elements of _balls in myPanel",
"<code>_balls.length == 20</code> in myPanel",
"<code>_balls.length == 10 <span style=\"font-family: arial,helvetica,sans-serif;\">in myPanel</span></code>"
] |
C
|
C is true. When you call ballCopy, it instantiates an array that is twice as large as _balls, which had length 10, then sets _balls to that new array.
|
canterbury_cs
|
canterbury_cs_0000452
|
Consider the following method and indicate what value is displayed from the initial call statement from another method:
System.out.println(Ackermann(2,3));
public int Ackermann(int n, int m) {<br> if (n==0)<br> return (m+1);<br> else if (m==0)<br> return (Ackermann(n-1,1));<br> else <br> return (Ackermann(n-1,Ackermann(n,m-1)));<br>}
|
[
"4",
"9",
"5",
"7"
] |
B
|
Ackermann's function is one of the earliest <em>hyper-exponential</em> recursive functions. The key to obtaining the correct answer is in keeping which parameter is which, straight. Maybe, rename them as "red" and "blue" (instead of n and m) to reduce confusion.
|
canterbury_cs
|
canterbury_cs_0000453
|
Which of the following algorithms use a divide-and-conquer strategy? (Circle all that apply.)
|
[
"Merge sort",
"Insertion sort",
"Binary search",
"Linear search"
] |
A
|
A and C are correct.
|
canterbury_cs
|
canterbury_cs_0000454
|
<pre lang="text/x-java">1. public BallPanel extends javax.swing.JPanel {
2. private Ball[] _balls;
3. private Ball[] _moreBalls;
4. public BallPanel(int numberOfBalls){
5. _balls = new Ball[numberOfBalls];
6. for (int i=0;i<_balls.length;i++)
7. _balls[i] = new Ball();
8. _moreBalls = _balls;
9. }
10. public Ball[] getBalls(){
11. return _balls;
12. }
13. public Ball[] getMoreBalls(){
14. return _moreBalls;
15. }
16. ...
</pre>
Which of the following statements is true, after executing the following code
(assuming Ball has a constructor that takes a Color argument).
<pre lang="text/x-java">BallPanel myPanel = new BallPanel(5);
myPanel.getMoreBalls()[0] = new Ball(java.awt.Color.pink);
</pre>
?
|
[
"The array<code> _balls</code> in myPanel is unchanged",
"The array _moreBalls in myPanel is unchanged",
"The first element of <code>_moreBalls</code> in myPanel is a new <code>Ball</code> constructed using <code>new Ball(java.awt.Color.pink);</code> and is not the same as the first element of <code>_balls</code> in myPanel;<code><br></code>",
"<code>myPanel.getBalls()[0] == myPanel.getMoreBalls()[0]</code>"
] |
D
|
Because of line 9, both _balls and _moreBalls refer to the same array. Therefore, if I re-assign an element in one array, the change shows up under the other. Moreover, since it is really only one array the elements are identical, so == will be true in this case.
|
canterbury_cs
|
canterbury_cs_0000455
|
Which of the following pairs of statements has two statements that are NOT equivalent?
|
[
"<code>&arr[0];</code> and <code>arr;</code>",
"<code>arr[0];</code> and <code>*arr;</code>",
"<code>*(arr + 1);</code> and <code>arr[1];</code>",
"<code>*(arr + 1);</code> and <code>*(arr) + sizeof(arr[0]);</code>"
] |
D
|
*(arr + sizeof) != *(arr) + sizeof
|
canterbury_cs
|
canterbury_cs_0000456
|
The following method, called maxRow(), is intended to take one parameter: a List where the elements are Lists of Integer objects. You can think of this parameter as a matrix--a list of rows, where each row is a list of "cells" (plain integers). The method sums up the integers in each row (each inner list), and returns the index (row number) of the row with the largest row sum. Choose the best choice to fill in the blank on <strong>Line 3</strong> so that this method works as intended:
<pre lang="text/x-java">public static int maxRow(List<List<Integer>> matrix)
{
int maxVec = -1; // Line 1
int maxSum = Integer.MIN_VALUE; // Line 2
for (int row = 0; row < __________; row++) // Line 3
{
int sum = 0; // Line 4
for (int col = 0; col < __________; col++) // Line 5
{
sum = sum + __________; // Line 6
}
if (___________) // Line 7
{
maxSum = __________; // Line 8
maxVec = __________; // Line 9
}
}
return maxVec; // Line 10
}
</pre>
|
[
"<code>matrix.size()</code>",
"<code>matrix[0[].size()</code>",
"<code>matrix[row][col]</code>",
"<code>matrix.length</code>"
] |
A
|
The blank on line three is the upper limit for the row count, controlling how many times the outer loop repeats. This should correspond to the number of rows in the <code>matrix</code>, or <code>matrix.size()</code>.
|
canterbury_cs
|
canterbury_cs_0000457
|
Which of the following run-times is NOT characteristic of a <em>feasible</em> (or <em>tractable</em>) algorithm?
|
[
"O(n<sup>2</sup>)",
"O(nlog<sub>2</sub> n)",
"O(2<sup>n</sup>)",
"O(n<sup>3</sup>)"
] |
C
|
Feasable (or tractable) algorithms are one whose time is expressed as a polynomial in terms of the input set size n. O(2<sup>n</sup>) is exponential in n.
|
canterbury_cs
|
canterbury_cs_0000458
|
Consider the code
<br><code>int i, *q, *p;</code>
<pre lang="text/x-c">p = &i;
q = p;
*p = 5;
</pre>
<br>Which of the following will print out “The value is 5.”?
|
[
"printf(\"The value is %d\", &i);",
"printf(\"The value is %d\", p);",
"printf(\"The value is %d\", *q);",
"printf(\"The value is %d\", *i);"
] |
C
|
q and p are sharing
|
canterbury_cs
|
canterbury_cs_0000459
|
Consider the code
<br><code>int *p, *q, i;</code>
<pre lang="text/x-c">i = 3;
q = p;
q = &i;
printf("The value of p is %d which points to %d.\n", p, *p);
</pre>
<br>Which of the following would you expect the program to print?
|
[
"The value of p is 0x3eee198e1e1 which points to 3.",
"The value of p is 0 which points to 0.",
"The value of p is -29389112111 which points to 3.",
"Segmentation fault"
] |
D
|
p was never assigned! While p and q are sharing for a while that does not mean they are the same.
|
canterbury_cs
|
canterbury_cs_0000460
|
Consider the following predicate (boolean) <em>accessor</em> function:
def blockedWithinOneMove(self):<br> if (not self.frontIsClear()):<br> return (True)<br> else:<br> self.move()<br> if (not self.frontIsClear()):<br> return (True)<br> else:<br> return (False)
<br>What is logically wrong with this predicate accessor function? The error is semantic and not syntactic.
|
[
"If the robot is blocked, after moving forward, this function incorrectly returns True.",
"If the robot is not blocked, after moving forward, this function incorrectly returns False.",
"This function returns True when is should return False, and returns False when it should return True.",
"In some cases, the preconditions do not match the postconditions; i.e. the state has changed."
] |
D
|
Accessor functions need to guarantee that the program state does not change. The robot moves forward to check for a wall, but fails to return to its starting location - which is necessary since this is an <em>accessor</em> method.
|
canterbury_cs
|
canterbury_cs_0000461
|
What value will this code print out on a 64-bit Linux machine with gcc?
<pre lang="text/x-c">int main
{
int key = get_key("zflsbi-k#gk!2*8jc5r:/bb&fc:j\x42\x20\x46\x4e");
printf("%d\n", key);
}
int get_key(char *bar)
{
</pre>
<code> // PRE: bar is != NULL</code><code><br> // POST: key is a happy number!</code>
<code> assert(bar);</code> <br><code> int key = 10;</code>
<pre lang="text/x-c"> char c[28];
memcpy(c, bar, strlen(bar));
</pre>
<br><code> assert(key <= INT_MAX && key > INT_MIN);</code>
<pre lang="text/x-c"> return key;
}
</pre>
|
[
"The code will not run; the asserts will trigger",
"10",
"1109411406",
"1313218626"
] |
D
|
There's a stack buffer overflow due to the memcpy, so the method will return 0x4e462042 (Little Endian); in decimal that is 1313218626.
|
canterbury_cs
|
canterbury_cs_0000462
|
<pre lang="text/x-java">1. import java.util.ArrayList;
2. public BallPanel extends javax.swing.JPanel {
3. private Ball[] _balls;
4. private ArrayList <Ball> _moreBalls;
5. public BallPanel(){
6. _balls = new Ball[20];
7. _moreBalls = new ArrayList<Ball>();
8. for (int i=0;i<10;i++) {
9. _balls[i] = new Ball();
10. _moreBalls.add(_balls[i]);
11. }
12. }
13. ...
</pre>
After line 11, what are the values of<code> _balls.length</code> and <code>_moreBalls.size()</code> respectively?
|
[
"10, 20",
"20, 10",
"10, 10",
"20, 20"
] |
B
|
_balls.length is set to 20 when the array is instantiated (in line 6) and is independent of the array contents.
<code>_moreBalls.size() <span style="font-family: arial,helvetica,sans-serif;">indicates the number of values stored in the ArrayList, which is 10 from the 10 adds in the loop.</span></code>
|
canterbury_cs
|
canterbury_cs_0000463
|
Consider this method skeleton for <code>findDigit()</code>:
<pre lang="text/x-java">/**
* Returns the number of times the digit d occurs in the decimal
* representation of n.
* @param n The number to consider (must be non-negative).
* @param d The digit to look for (must be 0-9).
* Returns the number of times d occurs in the printed representation
* of n.
*/
public int findDigit(int n, int d) // Line 1
{
int count = 0; // Line 2
if (__________) // Line 3
{
__________; // Line 4
}
while (n > 0) // Line 5
{
if (n % 10 == d) // Line 6
{
count++; // Line 7
}
return 1; // Line 8
}
return count; // Line 9
}
</pre>
<br><span style="font-family: arial, helvetica, sans-serif;">Select the best choice to fill in the blank on line 3 in this method to produce the correct behavior.</span>
|
[
"<code>d == 0</code>",
"<code>n == 0</code>",
"<code>n == 0 && d == 0</code>",
"<code>n < d</code>"
] |
C
|
The blank on line 3 checks a special case where the loop is never needed--when both the <code>n</code> passed in and the digit being search for are both zero, and the result of the method should be 1. Therefore, the condition should be <code>n == 0 && d == 0</code>.
|
canterbury_cs
|
canterbury_cs_0000464
|
Consider this method skeleton for <code>findDigit()</code>:
<pre lang="text/x-java">/**
* Returns the number of times the digit d occurs in the decimal
* representation of n.
* @param n The number to consider (must be non-negative).
* @param d The digit to look for (must be 0-9).
* Returns the number of times d occurs in the printed representation
* of n.
*/
public int findDigit(int n, int d) // Line 1
{
int count = 0; // Line 2
if (n == 0 && d == 0) // Line 3
{
__________; // Line 4
}
while (n > 0) // Line 5
{
if (n % 10 == d) // Line 6
{
count++; // Line 7
}
__________; // Line 8
}
return count; // Line 9
}
</pre>
<br><span style="font-family: arial, helvetica, sans-serif;">Select the best choice to fill in the blank on line 4 in this method to produce the correct behavior.</span>
|
[
"<code>return 0;</code>",
"<code>return 1;</code>",
"<code>return n;</code>",
"<code>return d;</code>"
] |
B
|
The test on line 3 checks a special case where the loop is never needed--when both the <code>n</code> passed in and the digit being search for are both zero. In this situation, the result of the method should be 1.
|
canterbury_cs
|
canterbury_cs_0000465
|
What algorithm does <em>mystery</em> implement when passed a list of values as its argument?
def helper (listOfValues, start):<br> largestSoFar = listOfValues[start]<br> largestIndex = start<br> current = start+1<br> while (current < len(listOfValues)):<br> if (listOfValues[current] > largestSoFar):<br> largestSoFar = listOfValues[current]<br> largestIndex = current<br> current = current + 1<br> return (largestIndex)
def mystery (listOfValues):<br> leftEdge = 0<br> while (leftEdge < (len(listOfValues)-1)):<br> biggestPosition = helper (listOfValues, leftEdge)<br> temp = listOfValues[biggestPosition]<br> listOfValues[biggestPosition] = listOfValues[leftEdge]<br> listOfValues[leftEdge] = temp
leftEdge = leftEdge + 1
return (listOfValues)
|
[
"List Reverser",
"Insertion Sort",
"Quicksort",
"Selection Sort"
] |
D
|
Helper is an implementation of <em>Find Largest</em>. By repeatedly invoking Find Largest, the <em>mystery</em> algorithm implements selection sort
|
canterbury_cs
|
canterbury_cs_0000466
|
Consider the following interface definition:
<pre lang="text/x-java">public interface Mover {
public int getX();
public int getY();
public void setLocation(int x, int y);
}
</pre>
Choose the best answer to describe the following implementation of that interface:
<pre lang="text/x-java">public class CartoonCharacter implements Mover{
private int x, y;
public int getX() {return this.x;}
public int getY() {return this.y;}
}
</pre>
|
[
"The class correctly implements the <code>Mover</code> interface because it says <code>implements Mover</code>.",
"The class does not correctly implement the <code>Mover</code> interface because it includes method bodies for <code>getX</code> and <code>getY</code>.",
"The class does not correctly implement the <code>Mover</code> interface because it has instance variables. ",
"The class does not correctly implement the <code>Mover</code> interface because it fails to define the <code>setLocation</code> method. "
] |
D
|
To implement a Java interface, a class must define all the methods required by the interface (or declare itself abstract).
<strong>Note:</strong> There is no appropriate topic for this question. Suggestion: TopicSimon-Interface-Java.
|
canterbury_cs
|
canterbury_cs_0000467
|
What does the following Python method do?
Note: lov stands for list of values.
def foo (lov):<br> listSize = len(lov)<br> current = 1<br> flag = True<br> while ((current < listSize) and flag):<br> if (lov[current] < lov[current-1]):<br> flag = False<br> current = current + 1<br> return (flag)
|
[
"Implements the sequential search algorithm.",
"Determines if the input list is sorted in ascending order.",
"Implements the selection sort algorithm.",
"Determines if the input list is sorted in descended order"
] |
B
|
Flag is set to true and when two adjacent list items are found to be out of place, with respect to a non-decreasing sorted order, flag is set to false.
|
canterbury_cs
|
canterbury_cs_0000468
|
Consider the following Java implementation of a Stack:
<pre lang="text/x-java">public class Stack<E> extends LinkedList<E>{
private int size=0;
public int size(){
return size;
}
public void push(E e){
add(e);
size+=1;
}
public E pop() {
size-=1;
return removeLast();
}
}
</pre>
What does the following code output?
<pre lang="text/x-java">Stack<Integer> q=new Stack<Integer>();
q.push(10);
q.push(20);
q.clear(); // clear() is inherited from LinkedList
System.out.println(q.size());
</pre>
|
[
"0",
"2",
"throws a Runtime exception",
"throws a checked exception (i.e. this code won't compile unless the code is surrounded by a try-catch block, or the method it is located inside declares that it throws the exception)"
] |
B
|
This is a classic case of using extends improperly. Remember that inheritance in Java (or any other Object-oriented language) creates an IS-A relationship. But, a Stack IS NOT a LinkedList, because there are things you can do to a LinkedList that you cannot do to a Stack, such as invoke clear().
Another way to think about this is that inheritance inherits ALL public methods, and allows those methods to be used by the subclass. For this Stack class, all of those inherited methods, such as clear(), can be called to change the state of the instance, but they don't know to pay attention to the size variable.
|
canterbury_cs
|
canterbury_cs_0000469
|
The<em> All-Pairs</em> list programming pattern typically runs in time?
|
[
"O(n<sup>2</sup>)",
"O(n)",
"O(n log<sub>2</sub> n)",
"O(1)"
] |
A
|
The <em>All-Pairs</em> programming pattern typically compares each element in a list to each other element in the list. Hence the first element is compared against n-1 other values. The second element is compared against n-2 other values, etc. Hence one gets a quadratic run time.
|
canterbury_cs
|
canterbury_cs_0000470
|
C++ uses
|
[
"call by value-return",
"call by value",
"call by value AND call by reference",
"call by reference"
] |
C
|
C++ defaults to call by value, but allows for special sytax to force call-reference.
|
canterbury_cs
|
canterbury_cs_0000471
|
Assume M and N are positive integers. What does the following code print?
<pre lang="text/x-java">int sum=0;
for (int j=0; j<M; j++) {
for (int i=0; i<N; i++) {
sum += 1;
}
}
System.out.println(sum);
</pre>
|
[
"M+N",
"M*N",
"M<sup>N</sup>",
"0"
] |
B
|
For positive integers M and N, this prints M*N
|
canterbury_cs
|
canterbury_cs_0000472
|
Consider the following:
public void foo (int x) {
...
}
What is x?
|
[
"A global variable.",
"A local variable.",
"The actual parameter.",
"The formal parameter."
] |
D
|
When invoking a method, the invokation contains the <em>actual</em> parameters, while the variables defined in the method signature define the <em>formal</em> parameters.
|
canterbury_cs
|
canterbury_cs_0000473
|
Java uses:
|
[
"call by reference",
"call by value",
"call by name",
"call by value-return"
] |
B
|
Java uses call by value. If the given parameter is an object, which is really a reference, then under call by value, the formal parameter is really just an alias (additional reference) to the actual parameter object.
|
canterbury_cs
|
canterbury_cs_0000474
|
<pre lang="text/x-java">1. public BallPanel extends javax.swing.JPanel {
2. private Ball[] _balls;
3. public BallPanel(int numberOfBalls){
4. _balls = new Ball[numberOfBalls];
5. for (int i=0;i<_balls.length;i++)
6. _balls[i] = new Ball();
7. }
8. public void ballCopy () {
9. Ball[] temp = new Ball[2 * _balls.length];
10. for (int j=0; j< _balls.length; j++0)
11. _temp[j] = _balls[j];
12. _balls = temp;
13. }
13. ...
</pre>
<span style="font-family: arial,helvetica,sans-serif;">What is the purpose of the <code>ballCopy</code> method?</span>
|
[
"It allows the user to copy a <code>Ball</code> in a <code>BallPanel</code>",
"It copies data in the <code>_balls</code> array",
"It increases the capacity of the <code>_balls</code> array while keeping existing data",
"It makes 2 copies of the elements in the <code>_balls</code> array"
] |
C
|
It doubles the length of the _balls array. It works by 1) instantiating temp, an array twice as large as _balls, 2) copying the data in _balls to the first half of temp, and 3) reassigning _balls to be temp. Useful if you want to have an array that can grow bigger when it gets full.
|
canterbury_cs
|
canterbury_cs_0000475
|
Consider this method skeleton for <code>findDigit()</code>:
<pre lang="text/x-java">/**
* Returns the number of times the digit d occurs in the decimal
* representation of n.
* @param n The number to consider (must be non-negative).
* @param d The digit to look for (must be 0-9).
* Returns the number of times d occurs in the printed representation
* of n.
*/
public int findDigit(int n, int d) // Line 1
{
int count = 0; // Line 2
if (__________) // Line 3
{
__________; // Line 4
}
while (n > 0) // Line 5
{
if (n % 10 == d) // Line 6
{
count++; // Line 7
}
__________; // Line 8
}
return count; // Line 9
}
</pre>
<br><span style="font-family: arial, helvetica, sans-serif;">Select the best choice to fill in the blank on line 8 in this method to produce the correct behavior.</span>
|
[
"n = n - d;",
"n = Integer.toString(n).substring(1);",
"n = n / 10;",
"n = n + d;"
] |
C
|
The loop in this method traverses through the digits in the specified number <code>n</code> from right-to-left--from least significant digit to most significant. Each iteration of the loop examines the rightmost digit that remains by using the modulo operator. To strip off and remove the least significant digit in <code>n</code> to prepare for the next iteration of the loop, use <code>n = n / 10;</code>.
|
canterbury_cs
|
canterbury_cs_0000476
|
Yuchi has the following code:
<pre lang="text/x-c">#DEFINE N 500
---- (other code skipped) ----
int arr[N][N]; int i; int j;
for(i = 0; i < N; i++)
{
for(j = 0; j < N; j++)
{
arr[i][j] = i + j;
}
}
</pre>
When he changes N to 500,000, his code crashes. Why?
|
[
"There is a memory leak in the code",
"<code>arr</code> is on the stack; it has run out of stack space",
"<code>arr</code> is on the heap; it has run out of heap space",
"With N that large, there will be at least one integer overflow in the code"
] |
B
|
arr is stored on the stack as it was statically allocated; the stack has limited space.
|
canterbury_cs
|
canterbury_cs_0000477
|
Suppose you have a Java array of ints. What is the worst-case time complexity of retrieving a value from a given location in the array?
|
[
"O(1)",
"O(log n)",
"O(n)",
"O(n log n)"
] |
A
|
Retrieving a value from an array can be done in constant time.
|
canterbury_cs
|
canterbury_cs_0000478
|
In Java, what word is used to refer to the current object, or to call one constructor from another in the same class?
|
[
"constructor",
"<code>new</code>",
"<code>null</code>",
"<code>this</code>"
] |
D
|
The reserved word <code>this</code> is used within a method or constructor to refer to the current object, or in the first statement of a constructor to call a different constructor in the same class.
|
canterbury_cs
|
canterbury_cs_0000479
|
Consider the following Java method:
<pre lang="text/x-java">public xxx printGreeting() { // 1
System.out.println("Hello!"); // 2
} // 3
</pre>
<span style="font-family: arial, helvetica, sans-serif;">The xxx in line 1 is best replaced by:</span>
|
[
"int",
"void",
"float",
"String"
] |
B
|
E is the correct answer, because the method does not return a value.
|
canterbury_cs
|
canterbury_cs_0000480
|
Which of the following statements about constructors is NOT true?
|
[
"All constructors must have the same name as the class they are in.",
"A constructor’s return type must be declared <code>void</code>.",
"A class may have a constructor that takes no parameters.",
"A constructor is called when a program creates an object with the <code>new</code> operator."
] |
B
|
In Java, a constructor does not have a return type, unlike a method.
|
canterbury_cs
|
canterbury_cs_0000481
|
Given the following Boolean expression:
<code>(jordan.getGridX() < 100) && (jordan.getGridY() >= 55)</code>
<span style="font-family: arial, helvetica, sans-serif;">Which of the following is logically equivalent?</span>
|
[
"<code>!((jordan.getGridX() >= 100) || (jordan.getGridY() < 55))</code>",
"<code>((jordan.getGridX() >= 100) || (jordan.getGridY() < 55))</code>",
"<code>!((jordan.getGridX() > 100) || (jordan.getGridY() <= 55))</code>",
"<code>!((jordan.getGridX() < 100) || (jordan.getGridY() >= 55))</code>"
] |
A
|
This question involves applying De Morgan's Law to factor out logical negation from a Boolean expression to find an equivalent expression.
|
canterbury_cs
|
canterbury_cs_0000482
|
Consider the following code segment:
<pre lang="text/x-java">if (!this.seesNet(LEFT) && this.seesFlower(AHEAD))
{
this.hop();
this.pick();
}
else
{
this.turn(RIGHT);
}
</pre>
Which of the following alternative versions is logically equivalent to (produce the same behavior as) the original?
|
[
"<pre lang=\"text/x-java\">if (this.seesNet(LEFT) || this.seesFlower(AHEAD))\n{\n this.turn(RIGHT);\n}\nelse\n{\n this.pick();\n this.hop();\n}\n</pre>",
"<pre lang=\"text/x-java\">if (!(this.seesNet(LEFT) && !this.seesFlower(AHEAD)))\n{\n this.turn(RIGHT);\n}\nelse\n{\n this.hop();\n this.pick(); \n}\n</pre>",
"<pre lang=\"text/x-java\">if (this.seesNet(LEFT) || !this.seesFlower(AHEAD))\n{\n this.turn(RIGHT);\n}\nelse\n{\n this.hop();\n this.pick();\n}\n</pre>",
"<pre lang=\"text/x-java\">if (this.seesNet(LEFT) && !this.seesFlower(AHEAD))\n{\n this.turn(RIGHT);\n this.turn(RIGHT);\n this.turn(RIGHT);\n}\nelse\n{\n this.pick();\n this.hop();\n}\n</pre>"
] |
C
|
The correct alternative has the same actions in both branches of the if statement, but in reversed positions--the true branch has moved to the false branch, and vice versa. At the same time, the logical condition in the if statement is the opposite of the original condition (by applying De Morgan's Law). Together, these two conditions produce a behaviorally equivalent block of code.
|
canterbury_cs
|
canterbury_cs_0000483
|
For any JUnit test class, when is the <code>setUp()</code> method executed?
|
[
"Only when explicitly invoked",
"Once before all the test methods are executed",
"Each time before a test method is executed",
"Only after the test class constructor method is executed"
] |
C
|
The <code>setUp()</code> method is used to set up the same starting conditions for all test methods in a test class. It is automatically executed before each test method, for every test method in the class.
|
canterbury_cs
|
canterbury_cs_0000484
|
In the Java language, what is the value of this expression?
<code>8 / 5 + 3.2</code>
|
[
"<code>3</code>",
"<code>3.2</code>",
"<code>4.2</code>",
"<code>4.8</code>"
] |
C
|
Because of precedence, the division operator is applied first. Since it is applied between two <code>int</code> values, the result is also an <code>int</code>, with any fractional part truncated. The result of the division is therefore 1. Next, the addition is performed, giving the result: 4.2.
|
canterbury_cs
|
canterbury_cs_0000485
|
Which of the following is <em>not</em> true about an <code>interface</code> in Java?
|
[
"Defines a type",
"Must include a constructor",
"Must not include method implementations",
"A class may implement more than one interface"
] |
B
|
Interfaces cannot be instantiated and cannot contain method bodies. As a result, they may not contain constructors.
|
canterbury_cs
|
canterbury_cs_0000486
|
Suppose you have a sorted list stored in consecutive locations in a Java array. What is the worst-case time complexity of inserting a new element in the list?
|
[
"O(1)",
"O(log n)",
"O(n)",
"O(n log n)"
] |
C
|
In order to make room for a new element in the array, it may be necessary to shift all the other elements.
<strong>Note:</strong> There is no skill tag for this type of question. Suggestion: Skill-Analyze-Code
|
canterbury_cs
|
canterbury_cs_0000487
|
Suppose you have a sorted list of numbers stored in a Java array of ints. What is the worst-case time complexity of searching for a given number in the list using binary search?
|
[
"O(1)",
"O(log n)",
"O(n)",
"O(n log n)"
] |
B
|
Binary search in a sorted array can be implemented in O(log n) time
<strong>Note: </strong>It is likely that the instructor went over this in class. If so, perhaps it should be tagged as Skill-Pure-Knowledge-Recall.
|
canterbury_cs
|
canterbury_cs_0000488
|
This sorting algorithm roughly orders elements about a pivot element and then sorts the subarray of elements less than the pivot and the subarray of elements greater than the pivot.
|
[
"selection sort",
"insertion sort",
"bubble sort",
"quick sort"
] |
D
|
Quick sort puts all elements less than the pivot element before the pivot and all elements greater after the pivot. Then it sorts these two halves.
|
canterbury_cs
|
canterbury_cs_0000489
|
What effect does the statement Option Explicit in the declaration section have on a Visual Basic module?
|
[
"The programmer is given the option to save code before the program is run.",
"All variables in the module have to be declared before use.",
"Global variables may be declared in the declarations section.",
"Procedures in the module may be accessed from other modules in the project."
] |
B
|
"When Option Explicit appears in a file, you must explicitly declare all variables using the Dim or ReDim statements. If you attempt to use an undeclared variable name, an error occurs at compile time.
Use Option Explicit to avoid incorrectly typing the name of an existing variable or to avoid confusion in code where the scope of the variable is not clear. If you do not use the Option Explicit statement, all undeclared variables are of Object type".
Ref http://msdn.microsoft.com/en-us/library/y9341s4f%28v=vs.80%29.aspx
|
canterbury_cs
|
canterbury_cs_0000490
|
Consider the following class definition.
<br><code>i<code>mport</code> java.util.Scanner; // 1</code>
<pre lang="text/x-java">public class SillyClass2 { // 2
private int num, totalRed, totalBlack; // 3
public SillyClass2 () { // 4
num = 0; // 5
totalRed = 0; // 6
totalBlack = 0; // 7
this.spinWheel(); // 8
System.out.print("Black: " + totalBlack); // 9
System.out.println(" and red: " + totalRed); // 10
} // 11
public void spinWheel () { // 12
Scanner kbd = new Scanner(System.in); // 13
System.out.println("Enter 1 or 0, -1 to quit."); // 14
num = kbd.nextInt(); // 15
while (num >= 0) { // 16
if (num == 0) // 17
totalRed++; // 18
else if (num == 1) // 19
totalBlack++; // 20
else System.out.println("Try again"); // 21
System.out.println("Enter 1 or 0, -1 to quit)."); // 22
num = kbd.nextInt(); // 23
} // 24
System.out.println("Thanks for playing."); // 25
} // 26
} // 27
</pre>
If line 1 is omitted, which other line(s) of code will cause compile errors?
|
[
"Lines 9, 10",
"Lines 13, 15, 23",
"Lines 14, 21, 22, 25",
"All of the above"
] |
B
|
Importing<code> java.util.Scanne</code>r allows us to declare, initialize, and use a <code>Scanner</code> object. It is not needed for <code>println</code> statements.
|
canterbury_cs
|
canterbury_cs_0000491
|
Consider the following class definition.
<pre lang="text/x-java">import java.util.Scanner; // 1
public class SillyClass2 { // 2
private int num, totalRed, totalBlack; // 3
public SillyClass2 () { // 4
num = 0; // 5
totalRed = 0; // 6
totalBlack = 0; // 7
this.spinWheel(); // 8
System.out.print("Black: " + totalBlack); // 9
System.out.println(" and red: " + totalRed); // 10
} // 11
public void spinWheel () { // 12
Scanner kbd = new Scanner(System.in); // 13
System.out.println("Enter 1 or 0, -1 to quit."); // 14
num = kbd.nextInt(); // 15
while (num >= 0) { // 16
if (num == 0) // 17
totalRed++; // 18
else if (num == 1) // 19
totalBlack++; // 20
else System.out.println("Try again"); // 21
System.out.println("Enter 1 or 0, -1 to quit)."); // 22
num = kbd.nextInt(); // 23
} // 24
System.out.println("Thanks for playing."); // 25
} // 26
} // 27
</pre>
Which sequence of inputs will cause the body of the while loop <strong><em>not</em></strong> to be executed?
|
[
"-1",
"0 -1",
"1 -1",
"0 1 -1"
] |
A
|
The loop test is <code>num >= 0</code>, so if the first number entered is less than 0, the loop will never be executed.
|
canterbury_cs
|
canterbury_cs_0000492
|
Consider the following class definition:
<pre lang="text/x-java">import java.util.Scanner; // 1
public class SillyClass2 { // 2
private int num, totalRed, totalBlack; // 3
public SillyClass2 () { // 4
num = 0; // 5
totalRed = 0; // 6
totalBlack = 0; // 7
this.spinWheel(); // 8
System.out.print("Black: " + totalBlack); // 9
System.out.println(" and red: " + totalRed); // 10
} // 11
public void spinWheel () { // 12
Scanner kbd = new Scanner(System.in); // 13
System.out.println("Enter 1 or 0, -1 to quit."); // 14
num = kbd.nextInt(); // 15
while (num >= 0) { // 16
if (num == 0) // 17
totalRed++; // 18
else if (num == 1) // 19
totalBlack++; // 20
else System.out.println("Try again"); // 21
System.out.println("Enter 1 or 0, -1 to quit)."); // 22
num = kbd.nextInt(); // 23
} // 24
System.out.println("Thanks for playing."); // 25
} // 26
} // 27
</pre>
Which sequence of inputs will cause line 18 <strong>not</strong> to be executed?
|
[
"0 10 -1",
"1 10 -1",
"0 1 -1",
"1 0 10 -1"
] |
B
|
Answers A and C are wrong, because the first number entered (0) will cause line 18 to be executed. Answer D is wrong because the first number entered (1) will cause the while loop to be executed, and the second time through the loop, the 0 input will cause line 18 to be executed. Answer E is wrong, because the first input (10) will cause the while loop to be executed, and the third input (0) will cause line 18 to be executed.
|
canterbury_cs
|
canterbury_cs_0000493
|
Consider the following class definition:
<pre lang="text/x-java">import java.util.Scanner; // 1
public class SillyClass2 { // 2
private int num, totalRed, totalBlack; // 3
public SillyClass2 () { // 4
num = 0; // 5
totalRed = 0; // 6
totalBlack = 0; // 7
this.spinWheel(); // 8
System.out.print("Black: " + totalBlack); // 9
System.out.println(" and red: " + totalRed); // 10
} // 11
public void spinWheel () { // 12
Scanner kbd = new Scanner(System.in); // 13
System.out.println("Enter 1 or 0, -1 to quit."); // 14
num = kbd.nextInt(); // 15
while (num >= 0) { // 16
if (num == 0) // 17
totalRed++; // 18
else if (num == 1) // 19
totalBlack++; // 20
else System.out.println("Try again"); // 21
System.out.println("Enter 1 or 0, -1 to quit)."); // 22
num = kbd.nextInt(); // 23
} // 24
System.out.println("Thanks for playing."); // 25
} // 26
} // 27
</pre>
Which sequence of inputs will cause line 20 <strong>not</strong> to be executed?
|
[
"0 0 10 -1",
"0 1 10 -1",
"0 10 1 -1",
"1 1 10 -1"
] |
A
|
Line A is correct because it is the only answer with no 1 in the sequence of inputs -- an input of 1 is necessary for line 20 to be executed.
|
canterbury_cs
|
canterbury_cs_0000494
|
What does the following Java code print:
<pre lang="text/x-java">int sum=0;
for (int j=0; j<3; j++) {
for (int i=0; i<4; i++) {
sum += 1;
}
}
System.out.println(sum);
</pre>
|
[
"6",
"4",
"12",
"8"
] |
C
|
12
|
canterbury_cs
|
canterbury_cs_0000495
|
What does the following Java code print?
<pre lang="text/x-java">int sum=0;
for (int i=1; i<=5; i++) {
sum += i;
}
System.out.println(sum);
</pre>
|
[
"0",
"5",
"10",
"15"
] |
D
|
The loop is infinte
|
canterbury_cs
|
canterbury_cs_0000496
|
Given the code
<pre lang="text/x-java">int x = 27;
int y = 12;
</pre>
the value of the expression <code>x <= y < x + y<span style="font-family: arial, helvetica, sans-serif;"> is:</span></code>
|
[
"1",
"0",
"false",
"an error"
] |
D
|
In Java, addition has a higher precedence than the relational operators. So the first step is to plug in the values and compute the results of the addition. Starting with the original expression <code>x <= y < x + y</code>, this yields <code>27 <= 12 < 39</code>. Relational operators are evaluated from left to right in Java, so the next step is to evaluate <code>27 <= 12</code>, which is true. So we now have the expression <code>true < 39</code>, which is invalid.
|
canterbury_cs
|
canterbury_cs_0000497
|
Which of the following is a list of syntactically legal Java class names?
|
[
"R2D2, Chameleon, public",
"R2D2, Chameleon, 23skidoo",
"r2d2, chameleon, public",
"r2d2, Iguana, _hello"
] |
D
|
To compile, Java class names must start with a letter or an underscore, followed by zero or more letters, numbers, or underscores. In addition, a class name must not be one of the Java reserved words, such as <code>public</code>.
|
canterbury_cs
|
canterbury_cs_0000498
|
Consider this section of code.
int a = 3, b = 4, c = 5;
x = a * b <= c
The expression contains an arithmetic operator, an assignment operator and a relational operator. Which is which?
|
[
"Arithmetic Assignment Relational \n = * <=",
"Arithmetic Assignment Relational \n * <= =",
"Arithmetic Assignment Relational \n <= * =",
"Arithmetic Assignment Relational \n * = <="
] |
D
|
operators are: multiply, assignment and less than or equal
|
canterbury_cs
|
canterbury_cs_0000499
|
Consider the following short program:
#include <stdio.h>
void f1(void);
int a;
void main(void)
{
int b;
a = b = 1;
f1();
printf("%d %d", a, b);
}
void f1(void)
{
int b = 3;
a = b;
}
A C program can use the same variable name in a number of places, as shown in this example, but it is always possible to work out to which actual variable a particular instance refers. This is described as
|
[
"the scope of a variable",
"the data type of a variable",
"the rules of precedence",
" block structuring"
] |
A
|
Scope is the largest region of program text in which a name can potentially be used without qualification to refer to an entity; that is, the largest region in which the name potentially is valid. Broadly speaking, scope is the general context used to differentiate the meanings of entity names. The rules for scope combined with those for name resolution enable the compiler to determine whether a reference to an identifier is legal at a given point in a file.
The scope of a declaration and the visibility of an identifier are related but distinct concepts. Scope is the mechanism by which it is possible to limit the visibility of declarations in a program. The visibility of an identifier is the region of program text from which the object associated with the identifier can be legally accessed. Scope can exceed visibility, but visibility cannot exceed scope. Scope exceeds visibility when a duplicate identifier is used in an inner declarative region, thereby hiding the object declared in the outer declarative region. The original identifier cannot be used to access the first object until the scope of the duplicate identifier (the lifetime of the second object) has ended.
Source http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fzexscope_c.htm
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.