# teaching machines

## CS 145 Lab 8 – Arrays

### Prelab

• There is no prelab problem this week.

### Reminder

• Show your completed lab 7 checkpoints to your instructor or TA in the first 20 minutes of this lab.

### Array usage

As discussed in class and in your textbook, arrays are simply number collections of data. We can have arrays of primitives and we can have arrays of objects. Making an array looks similar to making an object, except we must specify how many items we’ll store and our array variables are declared with type[]:

int[] counts = new int[100];
String[] names = new String[3];

Accessing the array and assigning an element of the array require an integer subscript, but otherwise these operations look very similar to referencing and assigning a plain old variable:

counts[0] = counts[0] + 1;
names[2] = "Slar";

We often need to march through an array one element at a time, which looks very similar to marching through a String one character at a time (in fact, Strings are really just char arrays):

for (int i = 0; i < names.length; ++i) {
System.out.println(names[i]);
}

### Swapping

Swapping values between variables or elements of an array is something we occasionally have to do. In assigning a new value to a variable, we lose the old value of the variable. So, before we lose the old value, we make a temporary copy of it. Here’s how we might swap two ints a and b:

int tmp = a;
a = b;
b = tmp;

Several of the problems below may benefit from swapping.

### Problems

Complete three of the following problems:

1. Rewrite the dice problem from the previous lab to use an array rather than six counters. (Your array must not contain wasted elements.)
2. Suppose you have a list of 10 names as Strings. (Hardcoded is fine.) Write code to randomly pick and print 5 of them, without repeats.
3. Suppose you have a String. (Hardcoded is fine.) Write code to count the frequency of each alphabetic letter. This problem is deftly solved if you can get the “serial number” of a letter, i.e., a = 0, b = 1, c = 2. Good news. Just subtract ‘a’ from your character and you’ll get that serial number. Character arithmetic is supported by Java. Print the frequencies after all characters have been processed.
4. Write a method named join that takes an array of Strings as its argument. It returns a String of the form “value0,value1,value2,…” No credit will be given if you do not have a method with the prescribed structure.
5. There are many algorithms for sorting data in an array. One simple one is called the selection sort. It can be described in pseudocode:
for each cell in the list
find the smallest value in the sublist starting at the current cell
swap that smallest value with the value in this cell

Translate this algorithm into Java and sort an array of ints.