Module 9: Arrays


Objectives

 

By the end of this module, for simple programs, you will be able to:

 


A group-of-items variable

 

First, recall our "box" analogy for a variable:

 

An array:

 

In-Class Exercise 1: Modify the above program (ArrayExample5.java) to include a sixth element so that the elements in order are: 36, 25, 16, 9, 4, 1. Print the elements and the array length.
 

Let's look at a few details carefully:

 

How to read aloud:

 

Let's now deliberately make a mistake to see what happens: we'll use an index that's "out of bounds"

 

In-Class Exercise 2: Edit, compile and execute the above program to see what happens.
 

 


Arrays and for-loops

 

Arrays go hand-in-hand with for-loops.

  • Note that the loop variable is used as the array index:

  • Here, the loop variable i takes values 0, 1, 2, 3, 4 in successive iterations.

  • For example, in the third iteration
    • i is 2.
    • Therefore, A[2] is given to System.out.println.
    • The value of A[2] is 9 (third element).
    • The value printed is therefore 9.

  • Here, we are cleverly using the for-loop variable i for two different purposes:
    • One is to serially traverse the array.
    • The second is to use its value in an arithmetic expression, whose value is eventually stored in the array.
 

We can use for-loops for filling in the elements of an array, e.g.,

 

In-Class Exercise 3: Trace through the first for loop iteration by iteration, and draw the contents of the array.
 

In-Class Exercise 4: Modify the above program to include a sixth element, 36. Also, change the order of elements so that the order is: 36, 25, 16, 9, 4, 1. That is, the first element in the array (A[0]) is 36, the second is 25 ... etc. Print the elements.
 

In-Class Exercise 5: For your modified array above, change the for-loop to print the elements in reverse order, starting with A[5], so that the elements are printed in the order 1, 4, 9, 16, 25, 36.
 


Arrays of double's

 

Consider the following example:

  • Here, we have declared an array variable A for an array of double values:

  • And created space for it (5 slots):

  • Then, we assigned values in a for-loop:

  • And used those values in printing:

 

In-Class Exercise 6: Modify the above code to compute the sum (of the first n terms) of the series s = 1 + 1/22 + 1/32 + ... + 1/n2. Then, compute the value 6*s and find its square root (perhaps using a calculator). Try this for different values of n. What do you think the series converges to?
 


Default values

 

Consider this program:

 

In-Class Exercise 7: What does the above program print? What do you conclude about the default values placed inside an array? Is it the same for integer arrays?
 


Assignment and copying with arrays

 

Consider the following program:

  • Here, we have created a second array B:

  • Each element is copied one by one:

 

In-Class Exercise 8: Draw out each array and trace through both for-loops showing, step-by-step in pictures, how elements get copied from one array to the other.
 

Now for something strange:

 

In-Class Exercise 9: What does the program print? Try it and see if you can explain the result.
 

About array copying and assignment:

  • Yes, it's a little strange.

  • When array variables are used in direct assignment, as in

    • The variable B gets associated with the same array space as A's.
    • We say that "A and B point to the same array space".

  • This is why B[0] and A[0] are the same "box".

  • This is true for the other slots.

  • For example, B[1] and A[1] are the same "box" too.
 

Lets see why this is true by looking at memory:

 

In-Class Exercise 10: Does it work the other way around?

What gets printed out?
 

In-Class Exercise 11: Consider this program:

What gets printed out?
 

Another example:

  public class CopyExample4 {
      public static void main(String[] argv) {
          double[] A = new double[5];

          for (int i = 0 ; i < 5 ; i++) {
              A[i] = 43770;
    	  }
          modifyArray(A);
          System.out.println(A[0]);
      }
  
      public static void modifyArray(double[] B) {
          B[0] = 0;
      }
  }      
In-Class Exercise 12: What gets printed out in the previous program? Why?
 

In-Class Exercise 13: Consider the following program:

  public class CopyExample5 {
      public static void main(String[] argv) {
          double[] A = {0,0,0,0,0};
          double[] B = {0,0,0,0,0};

          System.out.println(A + " " + B + " " + (A==B));
      }
  }
What gets printed out? Why?

Why do we not use == to compare Strings?

 


More examples

 

Example 1: let's write a program to "rotate" an array:

  • Thus, we want to shift each element into the next position rightwards.

  • The last element gets into the first position.

  • First, we'll use the help of an additional array to make this happen:

    • We first copied elements A[0],...,A[n-2] into locations ("boxes") B[1], ..., B[n-1].
    • Then, we copied A[n-1] into B[0].
    • The array B is in the desired form.
    • Lastly, we copied all of B into A so that A has the desired rotation.

  • It is possible to do without an additional array:

 

In-Class Exercise 14: Trace through the above example (RotateExample2.java) by hand to see how it works. Then, also trace through the version below and explain why it does not work:

 

Next, in the second example, we'll write code to reverse an array:

Here's a version that uses an additional array:

 

In-Class Exercise 15: Trace through the program above. Can you think of a way of achieving the reversal in the same array A? Try it!
 

Example 3: adding two arrays

  • Here, we have added two arrays element-by-element.

  • The resulting values are put into a third array (C).
 

In-Class Exercise 16: Trace through the program above. Then write another program (call it AdditionExample2) that takes an array A and computes the sum of the array A and its reversal, putting the result into array B. Can you do this without using a third array?
 

In-Class Exercise 17: Trace through the program below by hand.

What does it print?
 

In-Class Exercise 18: Trace through the program below by hand.

What does it print?
 

In-Class Exercise 19: Trace through the program below by hand.

What does it print? Look up the definition of factorial somewhere and relate that to the computation above.
 

Note: in the exercise above, we learned a few new things about using arrays:

  • Sometimes, we create one additional slot so that we can use the index A[n] when convenient.

  • A for-loop can have other variables that change with the loop besides the loop variable.
 


Multi-Dimensional Arrays

 

  public class MultDimArraysSyntax {
      public static void main(String[] argv) {
          double[][] A = new double[3][2];
          double[][] B = {{1, 2, 3}, {4, 5, 6}};
          
          // access and modification
          A[2][1] = 3.14;
          A[0][1] = 2.71;

          System.out.println(B[0][1] + " " + B[1][0]);
      }
  }
In-Class Exercise 20: What does the previous program print?
 

Multi-dimensional arrays:

  • Multiple indices, one per dimension.

  • Allocation of arrays: static with {{}}, or

  • dynamic with new type[x][y], for some size of the array, x and y.

  • Accessing a member of the array uses var[n][m] to access the nth row, and the mth column.

 

How do arrays look conceptually?

 

How do multi-dimensional arrays look in memory?

  • Two dimensional arrays are just an array of arrays.

  • Higher dimensions are just another layer of arrays.

 

What do you think the following program does?

  public class MultDimArrays {
      public static boolean hasValue(double[] a, double v) {
          for (int i = 0 ; i < a.length ; i++) {
              if (a[i] == v) {
                  return true;
              }
          }
          return false;
      }
      public static void main(String[] argv) {
          double[][] A = new double[3][2];

          A[2][1] = 3.14;
          A[0][1] = 2.71;

          System.out.println(hasValue(A[2], 3.14));
      }
  }
In-Class Exercise 21: Does this program compile without errors? What does it print out?
 

  public class MultDimArrays {
      public static boolean hasValue(double[] a, double v) {
          for (int i = 0 ; i < a.length ; i++) {
              if (a[i] == v) {
                  return true;
              }
          }
          return false;
      }
      public static void main(String[] argv) {
          double[][] A = new double[3][2];

          A[2][1] = 3.14;
          A[0][1] = 2.71;

          for (int i = 0 ; i < A.length ; i++) {
              System.out.println(hasValue(A[i], 3.14));
          }
      }
  }
In-Class Exercise 22: Does this program compile without errors? What does it print out?
 

Iterating through multidimensional arrays:

  • Often use nested for loops to iterate through the array.

  • A.length is the number of rows.

  • A[x].length is the number of columns.

  • To understand, look at the memory representation:

 

  public class MultDimArraysIteration {
      public static void main(String[] argv) {
          double[][] A = new double[3][2];

          A[2][1] = 3.14;
          A[0][1] = 2.71;

          for (int i = 0 ; i < A.length ; i++) {
              for (int j = 0 ; j < A[i].length ; j++) {
                  System.out.println(A[i][j]));
              }
          }
      }
  }
In-Class Exercise 23: What does this program print out? Modify it to print each column in each row on the same line, but each row on separate lines.
 

  public class GradingSpreadsheet {
      public static void main(String[] argv) {
          double[][] studentGrades = {{4, 3, 5, 2, 10},
                                      {8, 9, 9.5, 8, 0},
                                      {10, 10, 9, 9.5, 0}};
          String[] studentNames    = {"Larry", "Curly", "Moe"};

          // your code here!
      }
  }
In-Class Exercise 24: A simple spreadsheet app -- you have an array of student grades (each row contains the grades for each homework), and the student names. You can see that Larry did something mischievous on the last assignment. Lets do some simple processing:

  • Print each student's name, and their average grade over all homeworks.
  • Print the average grade for each homework.
  • For each of the homeworks, print the name of the student that got the highest grade.
  • Print the standard deviation of the grades for each student.
  • Create an array
    double[] weights = {0.2, 0.1, 0.2, 0.3, 0.2};
    with the same length as the number of homeworks. Compute a weighted grade, where the final grade for the student is determined by these weights on the homeworks.
  • Compute the grades "on a curve". How would you do this? Be creative; there are multiple ways.

If you have the time, re-implement these as separate methods that each return the value, or list, as appropriate.
 


Something different: designing and reading code

 

 

In-Class Exercise 25:

Conway's game of life is a "life simulation". The goal is to take as small a number of simple rules as possible, and watch emergent behavior and complex behavior come out of it! Read about it; especially the rules, and the images.

Lets represent the world as a 2D array of boolean values. True if a cell exists at that location, false otherwise.

The first phase of this exercise is to design your own game of life. Do not write any code! When you're designing a program, you're taking some specification, and figuring out how to structure your code.

  • What methods would you write? Try to break the problem down into smaller parts, each of which are more approachable. Try to break it down into as many methods as you can.
  • In each method which loops would you have?
  • In each method which conditionals would you have?

You won't write code to answer these questions, but you might write pseudo-code: code that ignores java syntax, and just includes the important conditionals and loop information. It lets you design without worrying about syntax.

The second phase is to get some practice reading code. At the super-secret-special-location the Prof. gives you, download a partially completed implementation.

  • Read the code. Understand the code.
  • Add the necessary logic that is missing to make it work!
  • Find examples of interesting game of life setups online. Add a few of them!

How is reading code different from writing code? Do you think it is useful? In what way?

 


Reading and writing

 

 

Let's look at an example and how to read the code:

  • First, look for the array declaration and identify the type (e.g, int or double etc):

    • Say to yourself, "A is an array that holds double's".
    • "B is an array that holds int's".

  • Then, look to see how much space is created:

    • Say to yourself, "A's size is 5, created using the new operator".
    • "A's elements are all initially 0".
    • "B's size is 5, directly initialized to particular values".

  • Now, check that, when variables are used to access array components (slots), the bounds are right:

 

Writing:

  • Writing the declaration:

    • No spaces between either the type (double), nor between the brackets.
    • A single space between the right bracket the array variable name.

  • Creating space:

    • A space on either side of the assignment operator, =.
    • A space on either side of the new reserved word.
    • The space after the double is optional. (Here, we have a space.)
    • No spaces for the size and brackets.

  • Prefer the use of the new operator except for small-ish arrays whose initial contents are known and fixed.

  • No spaces when using the values in an array:

 

Using the array's built-in length. Consider this variation:

  • We could either n or the array's length A.length.

  • So, which one should we use?
    • Generally, when the limit is a mathematically meaningful variable like n above, you can use n.
    • Otherwise, use the array's length.

  • Sometimes, using an array's length variable can make a program needlessly verbose.
    • For example, here's the array-reversal example using the length variable:

 

Variable names:

  • Here is the first length example, re-written with different variable names:

  • For a program this short, it is probably a bit verbose.

  • Notice: we used different names for the loop variables in the two for-loops.
 


When things go wrong

 

 

In-Class Exercise 20: Which of the following have errors (syntax or bugs) and what are they? Can you tell just by reading? Don't pay attention to the purpose - just whether the program will compile or run.

Program 1:

Program 2:

Program 3:

Program 4:

 

In-Class Exercise 21: The following program has multiple errors. See if you can spot them by reading. Then fix the errors by editing the program.