8:00 Quiz 8

One-page version suitable for printing.

Question 8-1

[5 pts] Suppose we were to execute f(n) for some number n using the following method.

public class Question1 {
  public static void f(int n) {
    int i = 1;
    while(i * i <= n) {
      i += 1;
    }
    IO.print(i - 1);
  }
}
In terms of n, how much time does this method take? Use Big-O notation to express your answer, and provide the tightest bound that you can.

Solution

Question 8-2

[5 pts] Suppose we were to execute the following run() method.

public class Question2 {
  public static void f(int n) {
    switch(n) {
    case 0:  return 5;
    case 1:  return 7;
    case 2:  return 9;
    case 3:  return 11;
    default: return 13;
    }
  }
  public static void run() {
    IO.println(f(2));
    IO.println(f(-2));
  }
}
What would it print?

Solution

Question 8-3

[5 pts] Suppose we were to execute the following run() method.

public class Question3 {
  public static int[] f(int[] arr) {
    arr = new int[arr.length];
    for(int i = 0; i < arr.length; i++) {
      arr[i] = 2 * i;
    }
    return arr;
  }
  public static void run() {
    int[] a = { 9, 8, 7 };
    int[] b = f(a);
    IO.println(a[1]);
    IO.println(b.length);
    IO.println(b[1]);
  }
}
What would it print?

Solution

Question 8-4

[15 pts] Write a class method named mode that takes an array of ints as a parameter and returns the integer that occurs in the array most frequently. For example, the following code fragment that uses your mode method should print 23.

int[] a = { 23, 34, 45, 23, 0, 23 };
IO.println(mode(a));
Your method should not call any other methods to accomplish this. It will need more than one loop to count the number of occurrences of each number in the array.

Solution