Java 2 FINAL EXAM

¡Supera tus tareas y exámenes ahora con Quizwiz!

20) A priority queue uses FIFO processing

Answer: False. Explanation: A priority queue uses priorities to determine which element comes off in a dequeue operation.

20) Merging two lists of n sorted elements would take O(n2) time.

Answer: False. Explanation: 2n elements would need to be examined and this is O(n).

1) An Abstract Data Type is a data structure, that is, it is the listing of the instance data and the visibility modifiers for those instance data.

Answer: False. An Abstract Data Type includes the data structure, but also includes the methods implemented to access/manipulate the data structure.

19) The pivot value selected in a quick sort should be the smallest element in the list.

Answer: False. Explanation: Choosing the smallest element causes the list to be divided unevenly. The best choice would be to choose the middle element, but often an element is chosen randomly because that takes less time.

21) Infinite recursion is impossible as long as you have a base case.

Answer: False. Explanation: If the recursive case is such that the base case will never be reached, then you have infinite recursion. For example: int bar(int n) { if (n < 0) return 0; else return bar(n); }

25) In a doubly linked list, every node has a pointer to both the first node in the list and the last node in the list.

Answer: False. Explanation: In a doubly linked list every node points to the node before it and the node after it.

5) A linked list that contains 6 Nodes will have 6 reference pointers.

Answer: False. Explanation: In order to access the linked list, there needs to be a 7th reference pointer at least, one that references the first item in the list.

24) A recursive method that doesn't return anything with result in infinite recursion.

Answer: False. Explanation: It is possible to have a void recursive method. (For example maybe it prints something rather than returning anything.)

3) Traversing a maze is much easier to do iteratively than recursively.

Answer: False. Explanation: One reason that recursion is appealing is that it automatically backtracks to the point of the last decision. In traversing a maze, when one reaches a dead end, the best place to continue is at the point of the previous intersection (or decision). So, backtracking is performed. To solve a maze iteratively requires implementing a backtracking mechanisms, which is available automatically in recursion.

13) A recursive algorithm is superior to an iterative algorithm because it is computationally more efficient.

Answer: False. Explanation: Recursion is more inefficient than iteration.

11) To simulate people waiting in a line you could use a stack.

Answer: False. Explanation: The FIFO access of a Queue is the same access of people waiting in line, the first person to enter will be the first to leave. So, simulations of any kind of line structure will use the Queue data structure. The Stack uses LIFO (last in, first out) access which does not make sense for a line.

12) After the instructions execute, x has the value 12.

Answer: False. Explanation: The Stack offers a last-in first-out access, so at the point when s.pop( ) is first executed, the item removed is the last item pushed onto s, or 19.

7) The recursive method to solve the Towers of Hanoi is usable only if the parameter for the number of disks is 7 or smaller.

Answer: False. Explanation: The Towers of Hanoi solution can be used for any sized disk as long as it is at least 1.

6) The linked list is superior to the array in all ways when it comes to implementing a list.

Answer: False. Explanation: The advantage of the linked list is that it is dynamic while the array is static. However, the array supports random access (the ability to access any element of the array easily) whereas a linked list does not support this (to access the 8th element, the first 7 elements must be traversed). So, the linked list has a major disadvantage, and even though is dynamic, many programmers choose to use an array to implement a list because of this drawback.

4) An array is a List Abstract Data Type.

Answer: False. Explanation: The array is a data structure that can be used to store a List of values, but the array does not have operations already implemented to perform List operations such as add to the end, or delete a given value.

16) The value 5 is returned by the last dequeue operation (denoted above with a d3 in comments).

Answer: False. Explanation: The dequeue operations remove the next item in the Queue, so the dequeue in d1 removes 3, the dequeue in d2 removes 5 and the dequeue in d3 removes 9.

11) Assume the method below is called initially with i = 0 public int question(String a, char b, int i) { if (i = = a.length( )) return 0; else if (b = = a.charAt(i)) return question(a, b, i+1) + 1; else return question(a, b, i+1); } The method returns 1 if char b appears in String a at least once, and 0 otherwise.

Answer: False. Explanation: The method compares each character in String a with char b until i reaches the length of String a. 1 is added to the return value for each match. So the method returns the number of times char b appears in String a.

6) Consider the following recursive sum method: public int sum(int x) { if(x = = 0) return 0; else return sum(x - 1) + 1; } If the base case is replaced with "if(x = = 1) return 1;" the method will still compute the same thing.

Answer: False. Explanation: The original method causes infinite recursion if called with a parameter < 0, but works properly if called with any parameter >= 0. With the new base case, the method now works properly if called with any parameter >= 1 but causes infinite recursion if the parameter < 1. So, sum(0) now differs from what it had previously.

10) We can define a list of int values recursively as: a list_item, followed by a comma, followed by a list where a list_item is any int value.

Answer: False. Explanation: The recursive definition does not include a base case so that all lists of int values will be infinitely long!

9) Since iterative solutions often use loop variables and recursive solutions do not, the recursive solution is usually more memory efficient (uses less memory) than the equivalent iterative solution.

Answer: False. Explanation: The recursive solution may use no local variables whatsoever, but the recursive solution usually uses parameters. Every time the method is called recursively, new parameters are required, and so recursively solutions usually use a substantially larger amount of memory than an iterative solution (it depends on how many times the method is called recursively).

24) A priority queue could not be implemented using an array.

Answer: False. Explanation: There are trade-offs between different implementations, but it is certainly possible to implement a priority queue using an array.

25) If method f1 calls method f2 calls method f3, we have indirect recursion.

Answer: False. Explanation: There is no recursion in that. Indirect recursion would be f1 calling f2 calling f1 again (and so on).

9) All classes are considered Abstract Data Types.

Answer: False. Explanation: To be considered an Abstract Data Type, the type must define a data structure and the methods to manipulate the data structure. However, a programmer does not have to set up a data structure in this way. For instance, if the instance data are made public, then there is no need to implement methods to manipulate those instance data, they can be directly modified from other classes. Therefore, just because a class exists does not mean that the class is an ADT

23) When a method is called by itself, it the second invocation uses the same storage space for local variables, so in effect the invocation share the variables.

Answer: False. Explanation: When a method is called recursively new local variables are created.

2) The push and enqueue operations are essentially the same operations, push is used for Stacks and enqueue is used for Queues.

Answer: False. While both operations are "add" or "insert" operations for their respective Abstract Data Types, they differ in that push always adds at the top (or front) of the Stack while enqueue always adds at the rear of the Queue

15) Aside from writing recursive methods, another way that recursion is often used is to define mathematical functions.

Answer: True . Explanation: Mathematics often defines functions recursively for simplicity.

2) The following method lacks a base case. public int noBaseCase(int x) { if(x > 0) return noBaseCase(x - 1) + 1; else return noBaseCase(x - 2) + 2; }

Answer: True. Explanation: A base case is a condition that, when taken, stops the recursion by not calling the method recursively. In the above method, there is a condition, but whether the condition is true or false, the method invokes itself recursively.

22) A priority queue is a dynamic data structure.

Answer: True. Explanation: A priority queue can grow and shrink during use, so it is a dynamic data structure.

13) After the instructions execute, z has the value 9.

Answer: True. Explanation: At that point that the int z = s.pop( ); executes, a previous s.pop( ); will have removed the most recently pushed item (4), so this pop removes the next most recently pushed item (9).

17) Recursion can be used when sorting an array of elements.

Answer: True. Explanation: Both merge sort and quick sort are often implemented recursively.

21) A stack could be simulated with a priority queue.

Answer: True. Explanation: Consider a priority queue where each item's priority is its time of arrival into the queue, and later times are given higher priority. This produces LIFO processing which is what a stack uses.

10) All Abstract Data Types are defined as classes in Java.

Answer: True. Explanation: In Java, all data are either primitives or classes. An ADT is a data structure, so it is more than just a primitive type, but a structure of different types. Therefore, the ADT must be defined in a class. Not all classes are necessarily ADTs, but all ADTs are defined as classes.

16) Merge sort and quick sort are more time efficient than insertion sort and selection sort.

Answer: True. Explanation: Merge sort has time efficiency O(nlogn) and quick sort, while it's worst case efficiency is O(n2) has average O(nlogn). O(nlogn) is more efficient than O(n2) which is what insertion and selection sort are.

4) Some problems are easier to solve recursively than iteratively.

Answer: True. Explanation: Since recursion performs backtracking automatically, any problem that requires backtracking is easier to solve using recursion. Such problems include traversing a maze and searching through a "search space", a topic covered in Artificial Intelligence and Advanced Algorithms courses. In some cases, it is easy to find a recursive solution and so the recursive solution is easier than the iterative solution.

8) A Koch snowflake of order = 1 can be drawn without recursion.

Answer: True. Explanation: The Koch snowflake of order 1 is made up of straight lines. It is not until the order is greater than 1 that recursion is applied.

19) The LinkedList class in the Java standard class library represents a list and is implemented using a linked list.

Answer: True. Explanation: The LinkedList class implements the List interface using a linked list implementation.

7) Queues and Stacks can be implemented using either arrays or linked lists.

Answer: True. Explanation: The Queue and the Stack are both Abstract Data Types, their method of implementation is immaterial, it is the operations (enqueue, dequeue, push, pop) that define them. So, both ADTs can be implemented using either arrays or linked lists.

8) In order to input a list of values and output them in order, you could use a Queue. In order to input a list of values and output them in opposite order, you could use a Stack.

Answer: True. Explanation: The Queue provides First-in First-out access, so the items would be accessed in the order that they were entered. The Stack provides Last-in First-out access, so the items would be accessed in the opposite order that they were entered.

15) After the code above executes, 4 elements remain in q.

Answer: True. Explanation: The constructor creates an initially empty Queue. Each enqueue operation adds one int to the Queue and each dequeue operation removes one int from the Queue. There are 7 enqueue operations and 3 dequeue operations, leaving 4 int values in q at the end.

3) The Abstract Data Type (ADT) is thought of as abstract because the operations that are to be implemented are separated from the actual implementation, that is, an ADT can be implemented in more than one way and that implementation is separate from how we might use the ADT.

Answer: True. Explanation: The importance of the ADT is that the operations are implemented as we would expect so that the operation is performed correctly even if we do not know how the operation is implemented. In this way, we assume that a Queue adds at the rear and removes from the front so that we have a FIFO access even though we do not know how the Queue is implemented itself.

5) The following two methods will both compute the same thing when invoked with the same value of x. That is, method1(x) = = method2(x). public int method1(int x) { if(x > 0) return method1(x - 1) + 1; else return 0; } public int method2(int x) { if(x > 0) return 1 + method2(x - 1); else return 0; }

Answer: True. Explanation: The only difference between the two methods is the order of the recursive call and adding 1 to the return value. The difference is denoted by calling the first method head recursive and the second tail recursive. So both methods will compute the same value, but arrive at the value in different ways.

17) If we replace each System.out.println statement (denoted in comments as d1, d2 and d3) with the statement q.enqueue(q.dequeue( )); q would contain the following values in the order given: 3, 2, 4, 5, 9, 1, 8

Answer: True. Explanation: The original order of int values in q is 3, 5, 9. At d1, the first item is dequeued and then enqueued resulting in 5, 9, 3. Two more enqueues result in 5, 9, 3, 2, 4. At d2 and d3, the first two items are dequeued and then enqueued resulting in 3, 2, 4, 5, 9. Finally, 1 and 8 are enqueued leaving q as 3, 2, 4, 5, 9, 1, 8.

23) There is no way to go backwards in a singly linked list.

Answer: True. Explanation: The pointers only point forward in a singly linked list. You would need a doubly linked list in order to go backwards.

18) A recursive sort typically divides the list into smaller sublists which are sorted recursively.

Answer: True. Explanation: The sublists are then combined.

14) The method below computes the value of x % y (x mod y) recursively, assuming that x and y not negative numbers. public int recursiveMod(int x, int y) { } if (x < y) return x; else return recursiveMod(x - y, y);

Answer: True. Explanation: The value x % y can be computed by continually subtracting y from x until x < y. Then, theresultisx. Forinstance,7%3=4%3=1%3=1.

12) The recursive method below would execute approximately log 2 n times for an initial parameter n. public void logcode(int n) { if (n > 1) logcode(n / 2); }

Answer: True. Explanation: This method recursively calls itself with n being half its original value. If n starts at 16, thesecondcallhasn=8,thethirdhasn=4,thefourthhasn=2,thefifthandfinalcallhasn=1. Ifnstartsat32,it adds one additional call. If we double n again, it only adds 1 more recursive call. This is a log 2 n behavior.

22) Infinite recursion can occur with indirect recursion.

Answer: True. Explanation: Two or more methods could call each other inifintely.

18) The first node in a linked list often requires special handling

Answer: True. Explanation: When inserting or deleting a node from the beginning of the linked list, a special case is required.

14) After the instructions execute, y has the value 4.

Answer: True. Explanation: When int y = s.pop() is executed, the most recently pushed item is 4, so 4 is popped off assigned to y.

1) A recursive method without a base case leads to infinite recursion.

Answer: True. Explanation: Without the base case, the recursive method calls itself without the ability to stop, and thus leads to infinite recursion.

4) Abstract Data Types have which of the following object-oriented features? a) Information hiding b) Inheritance c) Polymorphism d) Message Passing e) All of the above

Answer: a. Explanation: All of these answers are types of object-oriented features. An Abstract Data Type encapsulates a data structure and the methods to manipulate the data structure such that information hiding is preserved. Therefore, all ADTs make use of information hiding so that the data structure cannot be manipulated directly from outside of the ADT, but the other object-oriented features are not required.

14) Which of the following methods could be used to sum all of the items in the linked list? a) public int sumIt(Node temp) { while(temp != null) { sum += temp.info; temp = temp.next; } return sum; } b) public int sumIt(Node temp) { while(temp != null) { sum += temp.info; } return sum; } c) public int sumIt(Node temp) { while(temp != null) { sum++; temp = temp.next; } return sum; } d) public int sumIt(Node temp) { while(temp != head) { sum += temp.info; temp = temp.next; } return sum; } e) public int sumIt(Node temp) { while(temp != null) { if(next != null) sum += temp.info; temp = temp.next; } return sum; }

Answer: a. Explanation: Answer b does not advance temp to reference the next Node, and is therefore an infinite loop. Answer c counts the number of items in the list but does not sum up the values of these items. Answer d has the wrong loop condition and answer e counts all of the items in the list except for the last one.

24) If the method is called as patternRecognizer(x) where x is "aa", what will the result be? a) true b) false c) a NullPointerException d) a run-time error e) infinite recursion

Answer: a. Explanation: One of the base cases tests to see if the String has 2 characters and if so, returns true if the two characters are the same.

21) One operation that we might want to implement on a Stack and a Queue is full, which determines if the data structure has room for another item to be added. This operation would be useful a) only if the Queue or Stack is implemented using an array b) only if the Queue or Stack is implemented using a linked list c) only for a Queue d) only for a Stack e) none of the above, a full operation is not useful at all

Answer: a. Explanation: Since the array is a static sized object, if it becomes filled, then any add type of operation, whether it is a List insert, a Queue enqueue or a Stack push, should be prevented. This can be determined by first checking to see if the structure is full or not. This is not necessary if the data structure is implemented using a linked list since (we assume that) there will always be dynamic memory available to add a new element.

For questions 9 - 13, assume that int[ ] a = {6, 2, 4, 6, 2, 1, 6, 2, 5} and consider the two recursive methods below foo and bar. public int foo(int[ ] a, int b, int j) { } if (j < a.length) if (a[j] != b) return foo (a, b, j+1); else return foo (a, b, j+1) + 1; else return 0; public int bar(int[ ] a, int j) { if (j < a.length) return a[I] + bar(a, j+1); else return 0; } 11) What is the result of calling foo(a, 2, 9);? a) 0 b) 1 c) 2 d) 3 e) 4

Answer: a. Explanation: The method foo counts the number of occurrences of the int parameter in the second position in the array starting at the index given as the third parameter. So, foo(a, 2, 9) results in the base case being executed immediately because 9 = = a.length and the base case returns 0.

For questions 9 - 13, assume that int[ ] a = {6, 2, 4, 6, 2, 1, 6, 2, 5} and consider the two recursive methods below foo and bar. public int foo(int[ ] a, int b, int j) { } if (j < a.length) if (a[j] != b) return foo (a, b, j+1); else return foo (a, b, j+1) + 1; else return 0; public int bar(int[ ] a, int j) { if (j < a.length) return a[I] + bar(a, j+1); else return 0; } 10) What is the result of calling foo(a, 3, 0);? a) 0 b) 1 c) 2 d) 3 e) 4

Answer: a. Explanation: The method foo counts the number of occurrences of the int parameter in the second position in the array starting at the index given as the third parameter. So, foo(a, 3, 0) finds the number of 3s in a. There are none.

23) Which String below would result in patternRecognizer returning true? "abcba" "aaabbb" "abcde" "aabba" all of the above Strings will result in the method returning true

Answer: a. Explanation: The method patternRecognizer returns true if the String is a palindrome. This can be seen by analyzing the code. If the String has 1 character, or 2 characters which are equal, it returns true, otherwise if the first and last characters are the same, it recursively calls itself with the substring starting at character 1 and going to the second to last character (so, since in "abcba" the first and last characters are the same, the method is called recursively with the substring "bcb"). Only if the first and last characters do not match is false returned. The only palindrome in the list of options is a, "abcba".

16) What is returned by return head.info; ? a) 20 b) 11 c) 13 d) 19 e) 6

Answer: a. Explanation: The variable head references the first item, and so head.data is the instance data info of the first item, which stores 20.

12) Assume Node2 is defined as follows: int data; Node2 a, b; where a refers to the Node2 before this one in a linked list and b refers to the Node2 after this one in a linked list. Node2 could then be used to create which of the following variations of a linked list? a) singly linked list b) doubly linked list c) singly linked list with a header node d) singly linked list with a top node e) circularly linked list

Answer: b. Explanation: Because each item in the linked list has a reference to both the next node and the previous node, the list is known as a doubly linked list. With only a reference to the next node, the list would be known as a singly linked list. A list with a header node has a special node which has references to both the first node in the list and the last node in the list (often refered to as a head and a tail).

18) The solution to the Towers of Hanoi has a(n) _____ complexity. a) linear b) polynomial c) logarithmic d) exponential e) bad

Answer: d. Explanation: The complexity for Towers of Hanoi is 2^n - 1, which is known as exponential because, as n increases by 1, the number of moves doubles, or the complexity increases exponentially.

9) Assume Node temp references the last element of the linked list. Which of the following conditions is true about temp? a) (temp.info = = 0) b) (temp.next = = null) c) (temp = = head) d) (temp = = null) e) (temp.next = = null && temp.info = = null)

Answer: b. Explanation: Since temp is the last Node in the list, there is no next node, so temp.next is null. The answer in e is incorrect because temp references the last Node and this Node does have a value, so temp.info will equal some int value.

For questions 9 - 13, assume that int[ ] a = {6, 2, 4, 6, 2, 1, 6, 2, 5} and consider the two recursive methods below foo and bar. public int foo(int[ ] a, int b, int j) { } if (j < a.length) if (a[j] != b) return foo (a, b, j+1); else return foo (a, b, j+1) + 1; else return 0; public int bar(int[ ] a, int j) { if (j < a.length) return a[I] + bar(a, j+1); else return 0; } 13. What is the result of bar(a, 8);? a) 0 b) 5 c) 6 d) 12 e) 34

Answer: b. Explanation: The bar method recursively sums the elements of array a starting at the location of the second parameter (8 in this case). So, bar(a, 8) sums up only the last element in the array, 5, and so 5 is returned.

14) What does the following recursive method determine? public boolean question16(int[ ]a, int[ ] b, int j) { if(j = = a.length) return false; else if (j = = b.length) return true; else return question16(a, b, j+1); } a) Returns true if a and b are equal in size, false otherwise b) Returns true if a is larger than b, false otherwise c) Returns true if b is larger than a, false otherwise d) Returns true if a and b have no elements e) Returns the length of array a + length of array b

Answer: b. Explanation: The method returns true if the third parameter, j, is equal to the length of b but not equal to the length of a. Thus, the method returns true if the third parameter has reached the value indicating the end of array b butnottheendofarrayasothisistrueifaislargerthanb. Ifaandbareequallengthorifaisshorterthanb,falseis returned.

18) What will the statement head.next.next = head.next.next.next; accomplish? a) it will result in the list ending after 13 b) it will result in the value 13 being deleted from the list c) it will result in the list ending after 19 d) it will result in the value 19 being deleted from the list e) it will result in the list ending after 12

Answer: b. Explanation: The reference head.next.next is of the second Node in the list's next instance data, or 11's next. By setting this Node's next field to be head.next.next.next, this Node now references the Node storing 19 rather than 13, so it deletes 13 from the list.

17) What is the result to the linked list of the following instructions? Assume that newNode is a Node, already constructed. newNode.data = 1; newNode.next = head.next; head.next = newNode; a) The value 1 is inserted into the linked list before 20 b) The value 1 is inserted into the linked list after 20 and before 11 c) The value 1 is inserted into the linked list after 11 and before 13 d) The value 1 is inserted into the linked list after 13 and before 19 e) The value 1 is inserted into the linked list after 20 and the rest of the list is lost

Answer: b. Explanation: The statement newNode.next = head.next; sets the new node's next field to equal the second item in the list, so the new node, which stores 1, is inserted before 11. The statement head.next = newNode resets the first Node's next field to reference the new node, so 1 is now inserted after 20 and before 11.

2) A collection whose items are of different types is referred to as a(n) _______ type. a) homogeneous b) heterogeneous c) dynamic d) abstract e) vector

Answer: b. Explanation: The term heterogeneous means that the elements are different types. In Java, classes can store heterogeneous types, for instance one instance data might be an int and another a String and a third a double. Arrays on the other hand are homogeneous types because every element stored in the array is the same type.

10) Assume that the linked list has at least two Nodes in it. Which of the following instructions will return the second int value in the list? a) return head.info; b) return head.next.info; c) return head.next.next.info; d) return head.next.next.next.info; e) It is not possible to return the second int value in the list using head.

Answer: b. Explanation: The variable head references the first Node in the list, so that head.info is the first int value. The statement head.next references the second Node in the list, so head.next.info references the second Node's data item.

11) Assume Node temp is currently set equal to head. Which of the following while loops could be used to iterate through each element of a linked list? a) while (head != null) head = temp.next; b) while (temp != null) temp = temp.next; c) while (head != null) temp = temp.next; d) while (head != null) head = head.next; e) while (temp != null) head = head.next;

Answer: b. Explanation: To iterate through the list, we will use a different reference variable than head so that we do not lose our reference to the list, so we use temp instead. To iterate through the list, temp starts at head and continues until temp becomes null (it no longer references a node). To move to the next item in the list, temp is updated to be temp.next. The answer in d is correct but it loses the reference to the list and so is not what we would desire to do. The other loops have incorrect logic resulting in either infinite loops, or loops that cause run-time Exceptions.

For questions 4 - 7, refer to the following recursive factorial method. public int factorial(int x) { if (x > 1) return x * factorial (x - 1); else return 1; } 5) What is returned if factorial(0) is called? a) 0 b) 1 c) 2 d) nothing, factorial(0) causes infinite recursion e) nothing, factorial(0) produces a run-time error

Answer: b. Explanation: With factorial(0), (x > 1) is not true, so the base case is executed and 1 is returned. Therefore, even though ordinarily 0 * value = 0, the factorial(0) is computed as 1.

13) Which of the following methods could be used to count the number of items in the linked list? a) public int countIt(Node temp) { while(temp != null) { count += temp.info; temp = temp.next; } return count; } b) public int countIt(Node temp) { while(temp != null) { count++; } return count; } c) public int countIt(Node temp) { while(count != null) { count++; temp = temp.next; } return count; } d) public int countIt(Node temp) { while(temp != head) { count++; temp = temp.next; } return count; } e) public int countIt(Node temp) { while(temp != null) { if(next != null) count++; temp = temp.next; } return count; }

Answer: c. Explanation: Answer a sums all items in the array. Answer b does not advance temp to reference the next Node, and is therefore an infinite loop. Answer c properly counts each Node and moves on to the next Node. Answer d has the wrong loop condition and answer e counts all of the items in the list except for the last one.

19) A variation of a linked list is a circular linked list where the last Node in the list has next = head rather than next = null. One problem with this type of list is that a) it wastes memory space since head already points at the first Node, so the last one does not need to b) there is no ability to add a new Node at the end of the list since the last Node points at the first Node c) it is more difficult to traverse the list since the old terminating condition, (next = = null), is no longer true for the last node d) a header Node for this type of list is more complex e) all of the above

Answer: c. Explanation: Answers a, b and d are not true. This list uses no more memory than an ordinary linked list, adding a Node at the end requires the same amount of effort as before, and a header Node would be no different than before. However, answer c is true, the decision of whether there is another Node in the list or not can no longer be determined by testing (next = = null) since the last Node's next field is equal to head instead of null.

19) If traverse is first called with traverse(0, 0); what will the first recursive call of traverse be? a) traverse(0, 0); b) traverse(0, 1); c) traverse(1, 0); d) traverse(1, 1); e) traverse(0, -1);

Answer: c. Explanation: Since row and grid do not equal the bottom right node in the grid (that is, we haven't found the solution yet), the else clause, done = traverse(row + 1, column);, is executed, resulting in traverse(1, 0); being called.

8) Which of the following instructions would create an initially empty linked list? a) Node head = new Node( ); b) Node head = Node; c) Node head = null; d) Node head = new Node(0); e) Node head = list;

Answer: c. Explanation: The initial linked list will be empty, and so head should be null to indicate that there are no Nodes in the list yet. The answer in b is syntactically invalid, and the answers in a and d may be invalid depending on what parameter(s) the Node constructor expects, but in any event, the answers in a and d will create a Node, and therefore the initial list will not be empty.

24) This type of linked list is referred to as a a) singly linked list b) doubly linked list c) singly linked list with a header node d) doubly linked list with a header node e) singly linked list with a head and rear references

Answer: c. Explanation: The list is singly linked because there is only a next reference in each Node rather than a next and previous. Further, header is a header node for the list. The header node does contain a reference to head and rear, making answer e partly correct, but the references are part of a header node that includes the count (number of Nodes) in the list, so answer c is more correct.

For questions 1 - 2, use the following recursive method. public int question1_2(int x, int y) { if (x == y) return 0; else return question1_2(x-1, y) + 1; } 1) If the method is called as question1_2(8, 3), what is returned? a) 11 b) 8 c) 5 d) 3 e) 24

Answer: c. Explanation: The method computes x - y if x > y. The method works as follows: each time the method is called recursively, it subtracts 1 from x until (x == y) is becomes true, and adds 1 to the return value. So, 1 is added each time the method is called, and the method is called once for each int value between x and y.

8) What is wrong with the following recursive sum method? The method is supposed to sum up the values between 1 and x (for instance, sum(5) should be 5 + 4 + 3 + 2 + 1 = 15). public int sum(int x) { if(x = = 0) return 0; else return sum(x - 1) + x; } a) the base case should return 1 instead of 0 b) the recursive case should return sum(x - 1) + 1; instead of sum(x - 1) + x; c) the base case condition should be (x <= 0) instead of (x = = 0) d) the recursive case should return sum(x) + 1; e) the method should return a boolean instead of an int

Answer: c. Explanation: The method does not appropriately handle a negative parameter, such as sum(-5). The result is infinite recursion. We might define a negative parameter as something that should return 0, or allow a negative parameter to compute a negative sum as in: public int sum(int x) { } if(x = = 0) return 0; else if (x < 0) return -1 * sum(-x); else return sum(x - 1) + x;

For questions 9 - 13, assume that int[ ] a = {6, 2, 4, 6, 2, 1, 6, 2, 5} and consider the two recursive methods below foo and bar. public int foo(int[ ] a, int b, int j) { } if (j < a.length) if (a[j] != b) return foo (a, b, j+1); else return foo (a, b, j+1) + 1; else return 0; public int bar(int[ ] a, int j) { if (j < a.length) return a[I] + bar(a, j+1); else return 0; } 9) What is the result of calling foo(a, 2, 0);? a) 0 b) 1 c) 2 d) 3 e) 4

Answer: c. Explanation: The method foo counts the number of occurrences of the int parameter in the second position in the array starting at the index given as the third parameter. So, foo(a, 2, 0) finds the number of 2s in a. 2 appears 3 times in array a.

For questions 4 - 7, refer to the following recursive factorial method. public int factorial(int x) { if (x > 1) return x * factorial (x - 1); else return 1; } 6) How many times is the factorial method invoked if originally called with factorial(5)? Include the original method call in your counting. a) 1 b) 4 c) 5 d) 6 e) 7

Answer: c. Explanation: The method is first invoked with factorial(5), which in turn returns 5 * factorial(4), so factorial is invoked again, which in turn returns 4 * factorial(3), so factorial is invoked again, which in turn returns 3 * factorial(2), so factorial is invoked again, which in turn returns 2 * factorial(1), so factorial is invoked again, and finally factorial(1) invokes the base case and returns 1. So, factorial was invoked 5 times.

3) The following method should return true if the int parameter is even and either positive or 0, and false otherwise. Which set of code should you use to replace ... so that the method works appropriately? public boolean question3(int x) { ... } a) if (x = = 0) return true; else if (x < 0) return false; else return question3(x - 1); b) if (x = = 0) return false; else if (x < 0) return true; else return question3(x - 1); c) if (x = = 0) return true; else if (x < 0) return false; else return question3(x - 2); d) if (x = = 0) return false; else if (x < 0) return true; else return question3(x - 2); e) return(x = = 0);

Answer: c. Explanation: The method will recursively call itself subtracting 2 from x until x = = 0 or x < 0. If x = = 0, then it x - 2 * i == 0 (for some int value i) or x = = 2 * i, so x must be even. Otherwise, the recursion ends when x < 0, meaning that the original x was odd or less than 0.

20) Assume at some point in processing, grid's row 0 has become 3 3 3 1 1 1 0 0. Which direction will next be tried? a) up b) down c) left d) right e) none, the recursion ends at this point

Answer: d. Explanation: The current position is (2, 0), so it is not out of bounds or the lower right corner, and the current grid value was a 1, so the path is still valid. Therefore, the first instruction inside the else statement is executed, calling traverse with (row + 1, column) which represents the next position to the right.

15) Why is the following method one which has infinite recursion? public int infiniteRecursion(int n) { if (n > 0) return infiniteRecursion(n) + 1; else return 0; } a) Because there is no base case b) Because the base case will never be true c) Because the recursive call does not move the parameter closer to the base case d) Because the recursive call moves the problem further away from the base case e) None of the above, there is no infinite recursion in this method

Answer: c. Explanation: The recursive case has the method calling itself with the same parameter, and so n does not change, thus if (n > 0) is initially true, it will remain true.

5) Which of the following criticisms of an array is applicable to a Java array? a) It is an inefficient structure to access random elements b) It only supports First-in First-out types of accesses c) It is fixed in size (static) d) It cannot be used to create an Abstract Data Type such as a Queue or Stack e) All of the above

Answer: c. Explanation: The size of any array in Java is fixed when the array is instantiated. If, in adding elements to the array, it becomes filled, the array itself cannot change in size. A new array could be created with the old array elements moved into the new array, but this is inefficient.

20) Which of the following lists of operations is used to see the top item of a stack without removing it from the stack? a) push b) pop c) peak d) see e) top

Answer: c. Explanation: The three commands associated with a Stack are push, pop and peak. Push adds a new element to the top of the Stack, pop removes the top element off of the Stack and peak returns the top of the Stack without removing it.

21) Which of the following grids would be the result after traverse has completed all of its recursive calls? a) 11111100 00100100 00100110 00110010 00011000 00001111 b) 33333300 00300300 00300330 00330030 00033000 00003333 c) 77733300 00700300 00700330 00770030 00077000 00007777 d) 77777700 00300700 00300770 00330070 00033000 00003333 e) 33377700 00300700 00300770 00330070 00033000 00003333

Answer: c. Explanation: When a point in the maze is tried, its value is changed from 1 to 3, but if the end of the maze is found, the current row, column index is changed to 7. So the path is reflected as 7s and the tried but incorrect path is reflected as 3s and any untried parts of the path are reflected as 1s. For this maze, all legal path parts will have been tried before the solution is found, so the path leading to the exit is comprised of 7s and the remaining paths are comprised of 3s.

15) What will be returned by return head.next.next.next.info; ? a) 20 b) 11 c) 13 d) 19 e) 12

Answer: d. Explanation. The variable head references the first item, which stores 20, head.next references the second item, which stores 11, head.next.next references the third item, which stores 13, and head.next.next.next references the fourth item, which stores 19.

3) Which of the following is considered an Abstract Data Type? a) array b) reference variable c) any of the primitive types (e.g., int, double, char) d) ArrayList e) all of the above

Answer: d. Explanation: An Abstract Data Type comprises a data structure and the methods to manipulate and access the data structure. Of those listed, only the ArrayList combines both of these. The array is a data structure but without the methods (such as an insert method or a search method) while the reference variables and primitive types are data but not data structures.

For questions 1 - 2, use the following recursive method. public int question1_2(int x, int y) { if (x == y) return 0; else return question1_2(x-1, y) + 1; } 2) Calling this method will result in infinite recursion if which condition below is initially true? a) (x = = y) b) (x != y) c) (x > y) d) (x < y) e) (x = = 0 && y != 0)

Answer: d. Explanation: If (x < y) is true initially, then the else clause is executed resulting in the method being recursively invoked with a value of x - 1, or a smaller value of x, so that (x < y) will be true again, and so for each successive recursive call, (x < y) will be true and the base case, x == y, will never be true.

23) Previously, to iterate through a linked list, we used a while loop. Which of the following for-loops could replace the previous while loop that would start at head and go until temp == null? a) for(Node temp = header.front, int j = 0; j < header.count; temp = temp.next) { ... } b) for(int j = 0; j < header.count; j++) { ... } c) for(Node temp = header.front; temp != header.rear; temp = temp.next) { ... } d) for(Node temp = header.front, int j = 0; j < header.count; temp = temp.next, j++) { ... } e) for(Node temp = header.front, int j = 0; j < header.count && temp != header.rear; temp = temp.next, j++) { ... }

Answer: d. Explanation: Since header stores the number of elements in the linked list, we can start with a counter (j) at 0 and iterate while the counter is less than header.count, adding 1 after each iteration. We also need to make sure that we go from Node to Node. Only the loop in answer d accomplishes both of those steps. Note that answer c might seem right, but would stop once the loop has reached the last Node, not once the loop has finished with the last Node.

25) The expression LIFO stands for a) LIst FOundation b) LInk FOrmation c) Last In Front Of d) Last In First Out e) Long Int Float Object

Answer: d. Explanation: The Stack is a data structure in which items are added at the top end and removed from the top end, so the most recent item added is the first one removed (last in, first out). It is abbreviated as LIFO for convenience.

17) If there are 6 disks to move from one Tower to another, how many disk movements would it take to solve the problem using the recursive solution? a) 6 b) 13 c) 31 d) 63 e) 127

Answer: d. Explanation: The Towers of Hanoi solution requires using the previous solution twice + 1 extra move. To solve it for 1 disk, it takes 1 move. To solve it for 2 disks, it takes using the solution for 1 disk twice + 1 extra move, or 1 move + 1 move + 1 extra move = 3 moves. We capture this in the equation 2n - 1 where n is the number of disks. For 3 disks this takes 7 moves, for 4 disks this takes 15 moves, for 5 disks this takes 31 moves and for 6 disks this takes 63 moves.

16) If there are 2 disks to move from one Tower to another, how many disk movements would it take to solve the problem using the recursive solution? a) 0 b) 1 c) 2 d) 3 e) 4

Answer: d. Explanation: The Towers of Hanoi solution requires using the previous solution twice + 1 extra move. To solve it for 1 disk, it takes 1 move. To solve it for 2 disks, it takes using the solution for 1 disk twice + 1, or 1 move + 1 move + 1 move = 3 moves. We capture this in the equation 2n - 1 where n is the number of disks.

6) A linked list that stores int values would be comprised of a group of Nodes. We might define the Node by a) class Node { Node next; } b) class Node { int next; } c) class Node { int data; } d) class Node { int data; Node next; } e) class Node { int[ ] data; Node next; }

Answer: d. Explanation: The linked list stores int values, so each Node requires an int data type. Further, because it is a linked list, each node must contain a reference to the next Node, which is defined as Node next; where next is the reference.

22) Define the magnitude of a number as the location of the decimal point from the left of the number (that is, if a number has 4 digits followed by the decimal point, it will have a magnitude of 4). 100 would then have amagnitude of 3 and 55,555.555 would have a magnitude of 5. A partial recursive method is given below to compute a positive int parameter's magnitude. Which answer below is needed to complete the method? public int magnitude(double x) { if (x < 1) return 0; else return _______; } a) magnitude(x - 1) + 10; b) magnitude(x - 10) + 1; c) magnitude(x / 10) + 10; d) magnitude(x / 10) + 1; e) magnitude(x / 10) * 2;

Answer: d. Explanation: The method must count the number of digits to the left of the decimal point, so it continually divides the value by 10 until the value has no digits to the left of the decimal point (this is the case if value < 1). Each time the value is divided by 10, 1 is added to the return value. 55,555.555 will be divided by 10 five times before it becomes < 1, and thus return 5.

25) If the statement a.substring(1, a.length( ) - 1) were changed to be (a.substring(1, a.length( )), then the method would a) have infinite recursion unless the String were null b) always return true c) always return false d) return true only if all characters of the String were the same e) return true only the String had only two characters and they were the same

Answer: d. Explanation: The original method recursively calls itself with a substring equal to the String minus the first and last characters. This new version would recursively call itself with a substring equal to the String minus the first character. The method would return true if the first character of the String (or substring) equaled the last character. Since the substring for each recursive call is the same as the previous String less the first character, it winds up comparing each character in the String to the last in the String and returning true only if each character of the String equals the last character. This means all of the characters are the same.

For questions 4 - 7, refer to the following recursive factorial method. public int factorial(int x) { if (x > 1) return x * factorial (x - 1); else return 1; } 4) What is returned if factorial(3) is called? a) 0 b) 1 c) 3 d) 6

Answer: d. Explanation: With factorial(3), x > 1, so it returns 3 * factorial(2), with factorial(2), x > 1 so it returns 2 * factorial(1), with factorial(1), 1 is returned, so we have 3 * 2 * 1 = 6.

1) An array can be classified as what type of object? a) dynamic b) ordered c) first-in first-out d) heteogeneous e) collection

Answer: e. Explanation: An array stores a group of items and is dubbed a collection type (as opposed to other types that can store a single item). There are numerous collection types, the array being one composed only of homogeneous items (the array stores multiple items but they all must be of the same type).

22) In order to gain a last-in first-out access to data, which type of structure should be used? a) ArrayList b) Array c) Linked List d) Queue e) Stack

Answer: e. Explanation: The Stack is a data structure that allows only a last-in first-out (LIFO) access. Queues offer only a first-in first-out (FIFO) access. The Vector, Array and Linked List all offer any form of access desired.

7) The advantage of creating a BookList using a linked list instead of using an array is that the linked list a) offers easier access to a random element in the list b) uses less memory c) is easier to implement and debug d) can store types other than Books unlike the array e) is dynamic and so can be any size needed

Answer: e. Explanation: The advantage of the linked list over the array to implement such data structures as lists of items is that more items can always be added to it. This is known as a dynamic structure, unlike the fixed-sized array which is known as a static structure. Disadvantages of the linked list are that they are no easy to access randomly, unlike an array, and they are often more difficult to implement and debug than code using arrays. Further, while the linked list stores one Node for each item in the list, each Node requires at least two data items, the information, and a link to the next Node, so they may use more memory than an array.

For questions 9 - 13, assume that int[ ] a = {6, 2, 4, 6, 2, 1, 6, 2, 5} and consider the two recursive methods below foo and bar. public int foo(int[ ] a, int b, int j) { } if (j < a.length) if (a[j] != b) return foo (a, b, j+1); else return foo (a, b, j+1) + 1; else return 0; public int bar(int[ ] a, int j) { if (j < a.length) return a[I] + bar(a, j+1); else return 0; } 12) What is the result of calling bar(a, 0);? a) 0 b) 5 c) 6 d) 12 e) 34

Answer: e. Explanation: The bar method recursively sums the elements of array a starting at the location of the second parameter. Since the starting point is location 0, this call sums all elements of a (which equals 34).

For questions 4 - 7, refer to the following recursive factorial method. public int factorial(int x) { if (x > 1) return x * factorial (x - 1); else return 1; } 7) What condition defines the base case for this method? a) (x>1) b) (x==1) c) (x==0) d) (x<=0) e) (x<=1)

Answer: e. Explanation: The if condition is (x > 1) but this is the recursive case, so the base case is the opposite condition. The opposite of (x > 1) is (x <= 1).


Conjuntos de estudio relacionados

Intro to Health info-Ch.1 The Health Care Industry (Miyashita Yuu)

View Set

Βιολογία οικοσυστήματα

View Set

Computer Networking: A Top Down Approach Ch 2

View Set

Anatomy Final Exam Review Mastering Chapters 1-9

View Set