Practice exam #2

Ace your homework & exams now with Quizwiz!

The _____ case defined in a function stops recursion.

base

A _____ describes the operation performed by the recursive algorithm.

base case

Which catch syntax handles the unchecked exception, ArithmeticException?

catch (ArithmeticException except)

Which is the correct code to declare a catch-all handler?

catch (Throwable excpt) {...}

Which construct is the exception handler? try { if (val < 0) { throw new Exception("Error!"); } } catch (exceptionType excpt) { System.out.println(excpt.getMessage()); }

catch {...}

Which XXX will complete the code? public class RecursiveCalls { public static int convertToBinary(int num) { if (num == 0) { return 0; } else { return (num % 2 + 10 * convertToBinary(num / 2)); } } public static void main (String [] args) { System.out.print("The Binary number is: "); System.out.println(convertToBinary(7)); } }

convertToBinary(num / 2);

A stack overflow typically causes a program to _____.

crash

Identify the base case in the following code. public class FindMatch { public static int findMatch(char array[], int low, int high, char key) { if (high >= low) { int mid = low + (high - low) / 2; if (array[mid] == key) { return mid; } if (array[mid] > key) { return findMatch(array, low, mid, key); } else { return findMatch(array, mid + 1, high, key); } } return -1; } }

if (array[mid] == key)

Which XXX completes the power function? public class ExponentMethod { public static double raiseToPower(double base, double exponent){ if (exponent != 0) { XXX else { return (1/base) * raiseToPower(base, exponent+1); } } else { return 1; } } public static void main(String args[]){ int userBase; int userExponent; userBase = 2; userExponent = 4; System.out.println(userBase + " ^ " + userExponent + " = " + raiseToPower(userBase, userExponent)); } }

if (exponent > 0) { return (base * raiseToPower(base, exponent-1)); }

Which XXX defines a finally block to close a file? public class FileReadChars { public static void main(String[] args) { FileReader fileReader = null; String fileName; int charRead; charRead = 0; fileName = "file.txt"; try { System.out.println("Opening file " + fileName + "."); fileReader = new FileReader(fileName); System.out.print("Reading character values: "); while (charRead != -1) { charRead = fileReader.read; System.out.print(charRead + " "); } System.out.println(); } catch (IOException excpt) { System.out.println("Caught IOException: " + excpt.getMessage()); } finally { try{ XXX } catch (IOException excpt) { System.out.println("Caught IOException: " + excpt.getMessage()); } } } }

if (fileReader != null){ fileReader.close(); }

Which XXX will lead to stack overflow? public class RecursionExample { public static void reverseCount(int locNum) { XXX { locNum = locNum-1; System.out.println("hello"); reverseCount(locNum); } } public static void main(String[] args) { reverseCount(3); } }

if(locNum <= 3)

In the following code, the variable indentAmt _____ at each recursive call. public static int sum(int n, String indentAmt) { int sum = 0; if (n == 0) { System.out.println(indentAmt + "your value is: " + n); return 0; } else { System.out.println(indentAmt + "your value is: " + n); sum = n + sum(n - 1, indentAmt + " "); } System.out.println(indentAmt + "Returning pos = " + n); return sum; }

is incremented

In a list {25 31 14 58 66 47 98 40}, where i = 2 and k = 6, determine index j and the values stored in the left partition and the right partition.

j = 4, Left Partition = {14 58 66} and Right partition = {47 98}

What is output? public class StringLength { public static void lengthFun(String str) { int length = str.length(); System.out.println("Length : " + length); } public static void main(String[] args) { try { String str = null; lengthFun(str); } catch (Exception except) { System.out.println(except); } } }

java.lang.NullPointerException

What is the runtime complexity of the following code? NumberSearch(numbers, N, key) { mid = 0; low = 0; high = N - 1; while (high >= low) { mid = (high + low) / 2; if (numbers[mid] < key) low = mid + 1; else if (numbers[mid] > key) high = mid - 1; else return mid; } return -1; }

logarithmic

What XXX will generate the following output?Enter a value: 0 was not found. public class BinarySearch { public static int binarySearch(int [] list, int listSize, int key) { int mid; int low; int high; low = 0; high = listSize - 1; while (high >= low) { mid = (high + low) / 2; if (list[mid] < key) { low = mid + 1; } else if (list[mid] > key) { high = mid - 1; } else { return XXX; } } return -1; } public static void main(String [] args) { Scanner scnr = new Scanner(System.in); int [] list = {2, 4, 7, 10, 11, 32, 45, 87}; final int listSize = 8; int i; int key; int keyIndex; System.out.print("Enter a value: "); key = scnr.nextInt(); keyIndex = binarySearch(list, listSize, key); if (keyIndex == -1) { System.out.println(key + " was not found."); } else { System.out.println("Found " + key + " at index " + keyIndex + "."); } } }

mid

Binary search begins at the ______ of the range.

midpoint

What XXX will generate 1 3 5 7 8 9 as the output? public class SelectionSort { public static void selectionSort(int [] numbers, int numSize) { int i; int j; int index; int temp; for (i = 0; i < XXX; ++i) { index = i; for (j = i + 1; j < numSize; ++j) { if (numbers[j] < numbers[index]) { index = j; } } temp = numbers[i]; numbers[i] = numbers[index]; numbers[index] = temp; } } public static void main(String [] args) { int numbers [] = {9, 5, 7, 3, 1, 8}; final int N_SIZE = 6; int i; selectionSort(numbers, N_SIZE); for (i = 0; i < N_SIZE; ++i) { System.out.print(numbers[i] + " "); } System.out.println(); } }

numSize-1

To partition the input, quicksort chooses a _____ to divide the data into low and high parts.

pivot

Which of the following recursive methods will result in a stack overflow when main() calls fact(10)?

public static int fact(int n) { if (n == 100) return 1; else return n*fact(n-1); }

Which syntax defines a throws clause for exceptions that are not handled within a method?

public static void myMethod() throws Exception {...}

O(N2) has a ___ runtime complexity.

quadratic

What is the runtime complexity of the following code? SelectionSort(numbers, N) { for (i = 0; i < N; ++i) { indexSmallest = i; for (j = i + 1; j < N; ++j) { if (numbers[j] < numbers[indexSmallest]) { indexSmallest = j; } } temp = numbers[i]; numbers[i] = numbers[indexSmallest]; numbers[indexSmallest] = temp; } }

quadratic

An output statement can help debug recursive methods, especially if indented based on the _____.

recursion depth

After the following code prints "yz", what is the next call to remix()? public class RemixChars { public static void remix(String rmn, String chsn) { if (rmn.isEmpty()) { System.out.println(chsn + rmn); } else { for (int i = 0; i < rmn.length(); ++i) { remix((rmn.substring(0, i) + rmn.substring(i + 1, rmn.length())), (chsn + rmn.charAt(i))); } } } public static void main(String args[]) { remix("yz", ""); } }

remix("y", "z");

A recursive algorithm is based on _____ application(s) of the same algorithm on smaller problems.

repeated

What is output? public class RecursionExample { public static void printer() { System.out.println("hello"); printer(); } public static void main(String[] args) { printer(); } }

stack overflow

Sorting algorithms ______ elements in a list, comparing their values to sort.

swap

Which XXX is needed for enterNumber() to read a value from standard input? public int enterNumber() XXX{ int value; value = System.in.read(); return value; }

throws IOException

The _____ runtime of an algorithm is the runtime complexity for an input that results in the longest execution.

worst-case

If the list {3 9 7 18 1} is being sorted in ascending order using selection sort, what will be the list after completing the second outer loop iteration?

{1 3 7 18 9}

Which are the correct low and high partitions of the array {10 20 80 40 90 70} assuming the middle element as pivot?

{10 20 70 40} and {90 80}

Given a list of numbers {17 3 44 6 9}, identify the list after sorting in ascending order.

{3 6 9 17 44}

Given the list {23 6 19 92}, i = 0, and k = 3, what are the contents of the low partition? Assume quicksort always chooses the smallest element as the pivot.

{6}

Which is the sorted list for the array char check[] = {'A', 'b', 'C', 'a', 'Z', 'x'}?

{A, C, Z, a, b, x}

Identify the sorted list for A={ADRIAN ABBEY ADRIA ABBIE}.

{ABBEY ABBIE ADRIA ADRIAN}

Which of the following is a sorted list? {ALISHA ALISSON ALISON ALIYA} {154 125 652 700} {1 2 3 0} {Z X B A}

{Z X B A}

In the recursive function findMatch(), the first call is findMatch(array, 0, 4, key). What are the remaining function calls to find the character 'e'? public class FindMatch { public static int findMatch(char array[], int low, int high, char key) { if (high >= low) { int mid = low + (high - low) / 2; if (array[mid] == key) { return mid; } if (array[mid] > key) { return findMatch(array, low, mid, key); } else { return findMatch(array, mid + 1, high, key); } } return -1; } public static void main(String args[]){ char array[] = {'a','b','c','d','e'}; char key = 'e'; int result = findMatch(array, 0, 4, key); if (result == -1) { System.out.println("Element not found!"); } else { System.out.println("Element found at index: " + result); } } }

(array, 3, 4, key) and (array, 4, 4, key)

What is returned by System.in.read() when data is no longer available?

-1

What is output? public class WordScramble { public static void wordScramble(String rem, String scr) { if (rem.isEmpty()) { System.out.println(scr + rem); } else { for (int i = 0; i < rem.length(); ++i) { wordScramble((rem.substring(0, i) + rem.substring(i + 1, rem.length())), (scr + rem.charAt(i))); } } } public static void main(String args[]) { wordScramble("123", ""); } }

123 132 213 231 312 321

How many times is numberOfStudents() called if main() calls numberOfStudents(9)? public static void numberOfStudents(int num) { if (num >= 10) { System.out.println(num); } else { System.out.print("Bye"); numberOfStudents(num+1); } }

2

What is output? public class MathRecursive { public static void myMathFunction(int a, int r, int counter) { int val; val = a*r; System.out.print(val+" "); if (counter > 4) { System.out.print("End"); } else { myMathFunction(val, r, counter + 1); } } public static void main (String [] args) { int mainNum1 = 1; int mainNum2 = 2; int ctr = 0; myMathFunction(mainNum1, mainNum2, ctr); } }

2 4 8 16 32 64 End

Given the following list of sorted elements, how many elements of the list will be checked to find 25 using binary search? {12, 13, 15, 20, 23, 24, 25, 36, 40}

3

Given the list {12 30 40 0 47}, how many swaps will occur during the outer loop execution (i = 3)?

3

What is output for countNum(5);? public class CountNum { public static void countNum(int num) { if (num <= 0) { System.out.println("Done"); } else { System.out.print(num + " "); countNum(num - 2); } } }

5 3 1 Done

Using selection sort, how many times longer will sorting a list of 40 elements take compared to a list of 5 elements?

64

How many comparisons are required in an array of 16 elements, if quicksort always chooses the largest element as pivot? What is the depth of the recursion tree?

64, 15

If the list {29 18 45 7 16} is sorted in ascending order using selection sort, what will be the value of the 0th element after the first pass over the outer loop (i = 0)?

7

How many recursive partitioning levels are required for a list of 256 elements?

8

Using the Big-O runtime complexity, how many times longer will sorting a list of 15 elements take compared to sorting a list of 5 elements?

9

Which is true? -The FileOutputStream class includes println( ) -A PrintWriter object should be closed using close( ) -A PrintWriter constructor requires an OutputStream object -A FileOutputStream object opens an existing file

A PrintWriter constructor requires an OutputStream object

Which unchecked exception catches the error in the given code snippet? Object x = new Integer(0); System.out.println((String) x);

ClassCastException

Which is true? A program must import java.io.system to use System.out System.output.print() only outputs objects of type String The output of println() for an object reference includes all data stored in the object Data written to System.out are placed in a buffer and eventually output

Data written to System.out are placed in a buffer and eventually output

What is output? public class BaggageWeight { static void baggageWeight(int weight) { boolean value = false; try { while (!value) { if (weight > 30) { throw new Exception("Double Max Weight"); } if (weight > 15) { throw new Exception("Excess Weight"); } value = true; System.out.println("Accepted"); } } catch (Exception excpt) { System.out.println(excpt.getMessage()); } } public static void main(String[] args) { baggageWeight(42); } }

Double Max Weight

What is output? public class RecursiveFactorial { public static int factorial(int factValue) { if (factValue <= 0) { return 1; } else { return factValue*factorial(factValue-1); } } public static void main (String [] args) { int userVal = -5; System.out.println("Factorial = " + factorial(userVal)); } }

Factorial = 1

Which of the following activities can be accomplished using recursive algorithms?

Harvesting crops

What is output? (_ represents a blank space) String name = "Samantha"; System.out.printf("Her name is %6.3s", name);

Her name is ___Sam

Which of the following statements is true? IOException handles file-reading and file-closing exceptions The compiler closes a file once it encounters an error and terminates the program A finally block is executed only if a program encounters an error IOException closes the file stream during exception handling

IOException handles file-reading and file-closing exceptions

What is output? public class MathOps { public static int divOp(int num, int denom) throws Exception { if (denom == 0) { throw new Exception("Invalid div input"); } return num / denom; } public static double sqrtOp(double num) throws Exception { if (num < 0) { throw new Exception("Invalid sqrt input"); } return Math.sqrt(num); } public static void main(String[] args) { try { int x; int y; x = 4; y = 0; System.out.println(divOp(x, y)); System.out.println(sqrtOp((double)y)); } catch (Exception excpt) { System.out.println(excpt.getMessage()); System.out.println("Cannot compute operation"); } } }

Invalid div input Cannot compute operation

During the merge sort operation for the list {90 7 9 43 62 12 21 36}, at what left and right partition position is 21 added to the temporary list?

Left position is 2 and right position is 5

For the given lists, which option is correct? {60 70 85 14 90 100}, {50 60 70 79 84 100}, {20 21 22 19 18 17}

Nearly sorted, sorted, unsorted

What is the Big-O notation for the worst-case runtime? count = 0; extra = 0; for(i = 0; i < N; ++i) { if (numbers[i] < 0 ) { ++count; ++extra; } }

O(N)

What is the typical runtime of insertion sort?

O(N2)

What is the correct representation of O(5⋅N3+3⋅N+50)?

O(N3)

What is the simplified Big-O notation for 3⋅N3+O(2N2)?

O(N3)

What is output? public class DayEnd { static void timeHour(int hours) { int timeLeft; try { if (hours > 23) { throw new Exception("Invalid Hour!"); } timeLeft = 24 - hours; System.out.println("Time Left: "+timeLeft); } catch (Exception excpt) { System.out.println("Oops"); System.out.println(excpt.getMessage()); } } public static void main(String[] args) { timeHour(24); } }

Oops Invalid Hour!

Which calculation does not have a natural recursive solution?

Percentage

What is output? public class FindPerimeter { public static int perimeter(int arr[]) { int perimeter = 0; int i; for (i = 0; i < arr.length; i++) { perimeter += arr[i]; } return perimeter; } public static void main(String[] args) { int sides[] = {1,3,4,5}; try { System.out.println("Perimeter for given sides is " + perimeter(sides)); } catch (Exception excpt) { System.out.println("Caught Exception: " + excpt.getMessage()); } finally{ System.out.println("End"); } } }

Perimeter for given sides is 13 End

Which is true of Quicksort? Quicksort repeatedly partitions the input into low and high parts (each part unsorted). Quicksort chooses a pivot to divide the data into low and high parts. Quicksort divides the array into two parts to partition the input. Quicksort chooses a midpoint to divide the data into low and high parts.

Quicksort chooses a midpoint to divide the data into low and high parts.

For the list {Allen, Barry, Christopher, Daisy, Garry, Sandy, Zac}, what is the second name searched when the list is searched for Garry using binary search?

Sandy

_____ sort is a sorting algorithm that treats the input as two parts, a sorted part and an unsorted part, and repeatedly picks the proper next value to move from the unsorted part to the end of the sorted part.

Selection

What is output? (_ represents a blank space) int age = 50; System.out.printf("She is %4d years old", age);

She is __50 years old

Find the output statement that is used for debugging the following code: import java.util.Scanner; public class GuessMyAge { public static void myGuess(int low, int high, Scanner scnr, String indent) { int mid; char userAnswer; mid = (low + high) / 2; System.out.print("Is it " + mid + "? (</>/=): "); userAnswer = scnr.next().charAt(0); if ((userAnswer != '<') && (userAnswer != '>')) { System.out.println("Great!"); } else { if (userAnswer == '<') { System.out.println(indent + "User is younger."); myGuess(low, mid, scnr, indent + " "); } else { myGuess(mid + 1, high, scnr, indent + " "); } } } public static void main(String[] args) { Scanner scnr = new Scanner(System.in); System.out.println("Finding your age!"); myGuess(0, 100, scnr, " "); } }

System.out.println(indent + "User is younger.");

Which of the following is true about the merge sort algorithm?

The merge sort algorithm treats the input as two halves, recursively sorts each half, and then merges the sorted halves to produce a sorted list.

Identify the true statement about choosing a recursive method.

The problem naturally has a recursive solution.

Which of the following errors may lead to infinite recursion, causing the program to fail?

Writing a recursive method that does not always reach a base case


Related study sets

"Plethora" Most Nearly Means Drills

View Set

Planes & Axes of Movement - W.I.T.S

View Set