Chapter 3.3: Arrays

Chapter 3.3: Arrays · Study Questions
Index and lengthDeclarationReferencesOut-of-bounds errorsMean, median, modeSelection sortReversingMultidimensional arraysTransposeTic Tac Toe
Sercan KÜLCÜ · Giresun University · Computer Engineering

Multiple Choice · The Array Concept

Question 1: The Index Range

For the array created with int[] a = new int[8];, what is the valid index range and what is a.length?

B: Indexing starts at 0 and the last index is length − 1; length is the number of cells. A counts from 1, C takes the last index to be length (a[8] is out of bounds), and D confuses the number of cells with the last index.

Multiple Choice · Arrays in Java

Question 2: Which One Compiles?

Which of the following array declarations compiles?

D: The long form new int[]{…} can be used anywhere. A gives both a size and a list: array creation with both dimension expression and initialization is illegal. The short form in B is valid only in a declaration (illegal start of expression). C is C-language syntax; in Java the size is not written in the type.

Multiple Choice · Arrays in Java

Question 3: Skipping with continue

What does the program print?

static void printOdd(int[] array) {
  for (int i = 1; i < array.length; i++) {
    if (array[i] % 2 == 0)
      continue;
    System.out.print(array[i] + ",");
  }
  System.out.println();
}
// in main
printOdd(new int[]{5, 7, 10, 13, 12,
                 9, 9, 21, 22, 11});

C: continue skips the rest of the round and moves on to the next i: even elements (10, 12, 22) are not printed, and the loop goes on. Since the loop starts at i = 1, the first element, 5, is never checked (D). A is the behavior of break: the loop would end at the first even element (10). B applies the condition to the index instead of the element (i % 2 == 0).

Output Question · Arrays in Java

Question 4: Default Values and for-each

What does the program print? (java.util.Arrays is imported.)

double[] d = new double[2];
boolean[] b = new boolean[2];
String[] s = new String[2];
char[] c = new char[3];
System.out.println(d[0] + " " + b[1]
    + " " + s[0]);
System.out.println(c.length + d.length);
int[] x = {5, 6, 7};
for (int v : x) {
  v = v * 2;
}
System.out.println(Arrays.toString(x));
Show answer
0.0 false null
5
[5, 6, 7]

The cells of an array created with new get default values: double 0.0, boolean false, reference types null.

On the second line two ints are added: 3 + 2 = 5 (there is no concatenation, because both sides are numbers).

The for-each variable v is a copy of the element; writing to v does not change the cell. To write into the array you need a classic for loop and x[i] = x[i] * 2.

Output Question · Arrays in Java

Question 5: Reference or Copy?

What does the program print? In the end, which variable points to which array?

int[] a = {1, 2, 3};
int[] b = a;
b[0] = 9;
int[] c = Arrays.copyOf(a, 4);
c[1] = 7;
a = c;
a[2] = 5;
System.out.println(Arrays.toString(b));
System.out.println(Arrays.toString(c));
System.out.println((a == c) + " " + (a == b));
Show answer
[9, 2, 3]
[9, 7, 5, 0]
true false
stackabcheap9239750first arraycopy

b = a does not create a new array: b[0] = 9 changes the first array. Arrays.copyOf(a, 4) produces a new array with 4 cells (the extra cell is 0). After a = c, a points to the copy; a[2] = 5 now writes into the copy, and the first array, which b points to, stays [9, 2, 3].

Step-by-Step Trace · Arrays in Java

Question 6: Skipping Along

The loop's update expression is i += i, not i++. Which indices are read, and what does the program print?

50711021331249596217228119

The loop starts at 1, and with i += i each round does i = i + i: the index doubles.

5071i1021331249596217228119

i = 1: array[1] = 7 is printed; the 5 at index 0 is never read.

5071102i1331249596217228119

i = 1 + 1 = 2: array[2] = 10.

5071102133124i9596217228119

i = 2 + 2 = 4: index 3 is skipped, array[4] = 12.

50711021331249596217228i119

i = 4 + 4 = 8: array[8] = 22.

50711021331249596217228119

i = 16: 16 < 10 is false, the loop ends. Only 4 of the 10 elements were read. If the loop started at i = 0, we would get 0 + 0 = 0 and the loop would never end.

int[] array = {5, 7, 10, 13, 12, 9, 9, 21, 22, 11};
for (int i = 1; i < array.length; i += i) {
  System.out.print(array[i] + ",");
}
System.out.println();

Multiple Choice · Memory and Errors

Question 7: A Loop with <=

What happens when this code runs?

int[] d = new int[4];
for (int i = 1; i <= d.length; i++) {
  d[i] = i;
}

C: For i = 1, 2, 3 the cells are written; d[0] is never written and stays 0. At i = 4, 4 <= 4 is true and the access d[4] throws an exception. The compiler does not check index values (B); unlike C, Java does not let an out-of-bounds access pass silently (D). The correct pattern: for (int i = 0; i < d.length; i++).

Multiple Choice · Memory and Errors

Question 8: An Unreachable Array

After these four lines, which statement is true about the 1000-element array that was created first?

int[] p = new int[1000];
int[] q = p;
p = new int[5];
q = null;

A: The array is on the heap; p was bound to a new array and q became null, so no reference reaches the first array. The garbage collector can clean up such an object; when it will do so is unspecified. An array's size never changes (B), assigning null does not delete (C), and arrays live on the heap, not on the stack (D).

Output Question · Statistics Examples

Question 9: Mean and Median

What does the program print? What should the correct mean and median have been, and how do you fix the code?

int[] array = {7, 3, 9, 5, 1, 4};
int sum = 0;
for (int x : array) {
  sum += x;
}
double mean = sum / array.length;
Arrays.sort(array);
int n = array.length;
double median =
    (array[n / 2 - 1] + array[n / 2]) / 2;
System.out.println(mean + " " + median);
System.out.println(Arrays.toString(array));
Show answer
4.0 4.0
[1, 3, 4, 5, 7, 9]

sum = 29. 29 / 6 is integer division between two ints: 4; assigned to a double, it becomes 4.0. Median: n = 6 is even, the middle elements are array[2] = 4 and array[3] = 5; (4 + 5) / 2 is again integer division: 4.

The correct mean is 4.833… and the median 4.5: sum / (double) array.length and (array[n / 2 - 1] + array[n / 2]) / 2.0. Because Arrays.sort sorts the array in place, the last line prints the sorted array.

Step-by-Step Trace · Statistics Examples

Question 10: Mode: Counting Runs

In a sorted array, the mode (the most frequent value) is found by counting runs. After each round, what are the current run and the longest run, and what does the program print?

202162636495longest run

Start: the first element counts as both the current run and the longest run (length 1).

202162636495ilongest run

array[1] == array[0]: the run grows (2). Since 2 > 1, the longest run is updated.

202162636495ilongest run

6 ≠ 2: a new run starts, current = 6, count 1. 1 > 2 is false.

202162636495ilongest run

The run is 2 now, but 2 > 2 is false: on a tie, the first one found (2) is kept.

202162636495ilongest run

Run 3: 3 > 2 → the most frequent value is now 6.

202162636495ilongest run

9 starts a new run; the longest run does not change.

202162636495longest run

The loop ends. One pass is enough, because sorting put equal values side by side: O(n log n) sorting + O(n) scan.

int[] array = {2, 2, 6, 6, 6, 9}; // sorted
int best = array[0], bestCount = 1;
int current = array[0], currentCount = 1;
for (int i = 1; i < array.length; i++) {
  if (array[i] == array[i - 1]) {
    currentCount++;
  } else {
    currentCount = 1;
    current = array[i];
  }
  if (currentCount > bestCount) {
    bestCount = currentCount;
    best = current;
  }
}
System.out.println("Mode: " + best + " (" + bestCount + ")");

Step-by-Step Trace · Array Algorithms

Question 11: A Method with a Meaningless Name

What does foo(new int[]{7, 3, 9, 2, 1, 5}) print? What does the method do?

70abc3192231455

abc holds an index: at the start it is 0, so it points to 7.

i7031abc92231455

3 < 7: abc = 1.

i7031abc92231455

9 < 3 is false: no change.

i70319223abc1455

2 < 3: abc = 3.

i7031922314abc55

1 < 2: abc = 4.

i7031922314abc55

5 < 1 is false. At i = 6 the loop ends.

7031922314abc55

What is printed is not the smallest value (1) but its index: 4. The method finds the index of the smallest element; names like minIndex instead of abc and indexOfMin instead of foo make the code explain itself.

static void foo(int[] array) {
  int abc = 0;
  for (int i = 1; i < array.length; i++) {
    if (array[i] < array[abc]) {
      abc = i;
    }
  }
  System.out.println(abc);
}

Multiple Choice · Array Algorithms

Question 12: Comparisons in Selection Sort

On an array of 6 elements, how many times in total does selection sort perform the comparison array[j] < array[minIndex] in the inner loop? Does the initial order affect this number?

B: The rounds make 5 + 4 + 3 + 2 + 1 = n(n − 1) / 2 = 15 comparisons; the inner loop always runs to its end. Only the number of minIndex updates depends on the input. A counts n²; C is the behavior of insertion sort. The complexity is O(n²) in every case.

Step-by-Step Trace · Array Algorithms

Question 13: Tracing Selection Sort

What does the call selectionSort(new int[]{29, 10, 14, 37, 13}) print at the end of each round?

290101142373134

The method receives the array's reference: the swaps it makes change the caller's array.

100291142373134swapsorted part

i = 0: indices 1…4 are scanned; the smallest is 10 (index 1). Swap with array[0].

100131142373294swapsorted part

i = 1: among the remaining [29, 14, 37, 13] the smallest is 13 (index 4). It trades places with 29.

100131142373294with itselfsorted part

i = 2: 14 is already the smallest; minIndex stays i, the swap is with itself, and the array does not change.

100131142293374swapsorted part

i = 3: 29 < 37, swap. The outer loop runs length − 1 = 4 rounds: the last element is automatically in place.

static void selectionSort(int[] array) {
  for (int i = 0; i < array.length - 1; i++) {
    int minIndex = i;
    for (int j = i + 1; j < array.length; j++) {
      if (array[j] < array[minIndex]) {
        minIndex = j;
      }
    }
    int temp = array[minIndex];
    array[minIndex] = array[i];
    array[i] = temp;
    System.out.println(Arrays.toString(array));
  }
}

Spot the Bug · Array Algorithms

Question 14: A Bug in Reversing

The method was written to reverse the array {1, 2, 3, 4, 5}. What does Arrays.toString(a) print after reverse(a)? Where is the bug?

static void reverse(int[] d) {
  for (int i = 0; i < d.length; i++) {
    int t = d[i];
    d[i] = d[d.length - 1 - i];
    d[d.length - 1 - i] = t;
  }
}
Show answer
[1, 2, 3, 4, 5]

The loop goes over the whole array: at i = 0 and 1 the ends are swapped ([5, 4, 3, 2, 1]), at i = 2 the middle element is swapped with itself, and at i = 3 and 4 the same pairs are swapped again, so the array returns to its old state.

The fix: go over only half of the array.

for (int i = 0; i < d.length / 2; i++) {

The output becomes [5, 4, 3, 2, 1]; it also works for a 4-element array ([4, 3, 2, 1]). n / 2 swaps: O(n).

Multiple Choice · Array Algorithms

Question 15: Passing an Array and an int to a Method

What does the program print?

static void f(int[] d, int x) {
  d[0] = x;
  d = new int[]{0, 0};
  d[1] = x;
  x++;
}
// in main
int[] a = {1, 2};
int k = 5;
f(a, k);
System.out.println(a[0] + " " + a[1] + " " + k);

D: Java passes everything by value: d is a copy of the reference, x is a copy of the number. d[0] = x changes the original array (5). d = new int[]{0, 0} only binds the local copy to a new array; d[1] = x writes into that new array. x++ does not affect k either.

Output Question · Multidimensional Arrays

Question 16: A Jagged Array

What does the program print?

int[][] m = new int[3][];
for (int i = 0; i < m.length; i++) {
  m[i] = new int[i + 2];
  for (int j = 0; j < m[i].length; j++) {
    m[i][j] = i * j;
  }
}
int t = 0;
for (int[] row : m) {
  t += row[row.length - 1];
}
System.out.println(m[2].length + " " + t);
System.out.println(Arrays.toString(m[1]));
Show answer
4 8
[0, 1, 2]
m[0]00m[1]012m[2]0246last elements: 0 + 2 + 6

new int[3][] creates only three row references (null); the rows are allocated in the loop with lengths 2, 3 and 4. Because the inner loop uses m[i].length, each row is filled up to its own length. The element of the for-each is a row, an int[]; the sum of the last elements is 0 + 2 + 6 = 8.

Multiple Choice · Multidimensional Arrays

Question 17: Number of Rows and Columns

What does the program print?

int[][] m = {{1, 2, 3}, {4, 5, 6}};
System.out.println(m.length + " "
    + m[1].length + " " + m[1][0]);

C: A 2D array is an array of arrays: m.length is the number of rows (2), m[1] is the second row and its length is 3, and m[1][0] is the first element of the second row, 4. A and D confuse rows with columns; B reads m[1][0] from the first row.

Step-by-Step Trace · Multidimensional Arrays

Question 18: Tracing a Transpose

The transpose of a 2×3 matrix is copied cell by cell. Which cell is written at each step, and what does the program print?

m (2×3)t (3×2)123456000000

t is created with 3 rows and 2 columns: its number of rows is the original matrix's number of columns. The cells are 0.

m (2×3)t (3×2)123456100000

m[0][0] = 1 → t[0][0].

m (2×3)t (3×2)123456102000

m[0][1] = 2 → t[1][0]: the indices swap places.

m (2×3)t (3×2)123456102030

m[0][2] = 3 → t[2][0]. The first row of m has become the first column of t.

m (2×3)t (3×2)123456142030

i = 1: m[1][0] = 4 → t[0][1].

m (2×3)t (3×2)123456142530

m[1][1] = 5 → t[1][1] (the diagonal stays in place).

m (2×3)t (3×2)123456142536

m[1][2] = 6 → t[2][1]. The loops end.

m (2×3)t (3×2)123456142536

Arrays.deepToString prints nested arrays; toString would print only the identities of the rows.

int[][] m = {{1, 2, 3}, {4, 5, 6}};
int[][] t = new int[m[0].length][m.length];
for (int i = 0; i < m.length; i++) {
  for (int j = 0; j < m[0].length; j++) {
    t[j][i] = m[i][j];
  }
}
System.out.println(Arrays.deepToString(t));

Spot the Bug · Application: Tic Tac Toe

Question 19: Checking for a Winning Row

What does rowWon(t, 'X') return on a board whose bottom row is all X? Find the bug and fix it.

static boolean rowWon(char[][] t,
                          char o) {
  for (int i = 0; i < 3; i++) {
    if (t[i][0] == o && t[i][1] == o
        && t[i][2] == o) {
      return true;
    } else {
      return false;
    }
  }
  return false;
}
// in main
char[][] t = {{'O', ' ', 'O'},
              {' ', 'O', ' '},
              {'X', 'X', 'X'}};
System.out.println(rowWon(t, 'X'));
Show answer
false

The first row (O, blank, O) does not satisfy the condition, and the return false in the else branch ends the method in the first round: the 2nd and 3rd rows are never looked at.

The fix: remove the else part; the "no" verdict is given only after all rows have been checked, after the loop.

for (int i = 0; i < 3; i++) {
  if (t[i][0] == o && t[i][1] == o
      && t[i][2] == o) {
    return true;
  }
}
return false;

The corrected method returns true.

Multiple Choice · Application: Tic Tac Toe

Question 20: Short-Circuiting and Bounds

The user entered 4 5; row = 3 and col = 4. What happens when the do-while condition is evaluated?

do {
  row = scanner.nextInt() - 1;
  col = scanner.nextInt() - 1;
} while (row < 0 || row > 2
      || col < 0 || col > 2
      || board[row][col] != ' ');

A: || short-circuits: it evaluates from left to right and stops at the first true. Since row > 2 is true, board[row][col] is never read and the loop asks for new input. If the cell check had been written before the bounds checks, the answer would be B.

The End

Chapter 3.3: Arrays: Study Questions
Lecture slides: Chapter 3.3: Arrays · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.