Simple Arrays: Eric Roberts CS 106A May 4, 2012
Simple Arrays: Eric Roberts CS 106A May 4, 2012
Simple Arrays: Eric Roberts CS 106A May 4, 2012
Simple Arrays
Introduction to Arrays
An array is a collection of individual data values with two distinguishing characteristics:
1. An array is ordered. You must be able to count off the values: here is the first, here is the second, and so on. 2. An array is homogeneous. Every value in the array must have the same type.
The individual values in an array are called elements. The type of those elements (which must be the same because arrays are homogeneous) is called the element type. The number of elements is called the length of the array.
Each element is identified by its position number in the array, which is called its index. In Java, index numbers always begin with 0 and therefore extends up to one less than the length of the array.
where type is the element type, name is the array name, and n is an integer expression indicating the number of elements. This declaration syntax combines two operations. The part of the line to the left of the equal sign declares the variable; the part to the right creates an array value with the specified number of elements and then assigns it to the array variable.
Even though the two operations are distinct, it will help you avoid errors if you make a habit of initializing your arrays when you declare them.
This easiest way to visualize arrays is to think of them as a linear collection of boxes, each of which is marked with its index number. You might therefore diagram the intArray variable by drawing something like this:
intArray
0
0
0
1
0
2
0
3
0
4
0
5
0
6
0
7
0
8
0
9
Java automatically initializes each element of a newly created array to its default value, which is zero for numeric types, false for values of type boolean, and null for objects.
Array Selection
Given an array such as the intArray variable at the bottom of this slide, you can get the value of any element by writing the index of that element in brackets after the array name. This operation is called selection. You can, for example, select the initial element by writing
intArray[0]
The result of a selection operation is essentially a variable. In particular, you can assign it a new value. The following statement changes the value of the last element to 42:
intArray[9] = 42;
intArray
0
0
0
1
0
2
0
3
0
4
0
5
0
6
0
7
0
8
42 0
9
Selecting the length field returns the number of elements. As an example, you can reset every element in intArray to zero using the following for loop:
for (int i = 0; i < intArray.length; i++) { intArray[i] = 0; }
/** * Calculates the sum of an integer array. * @param array An array of integers * @return The sum of the values in the array */ private int sumArray(int[] array) { int sum = 0; for (int i = 0; i < array.length; i++) { sum += array[i]; } return sum; }
/** * This program creates a pattern that simulates the process of * winding a piece of colored yarn around an array of pegs along * the edges of the canvas. */ public class YarnPattern extends GraphicsProgram {
public void run() { initPegArray(); int thisPeg = 0; int nextPeg = -1; while (thisPeg != 0 || nextPeg == -1) { nextPeg = (thisPeg + DELTA) % N_PEGS; GPoint p0 = pegs[thisPeg]; GPoint p1 = pegs[nextPeg]; GLine line = new GLine(p0.getX(), p0.getY(), p1.getX(), p1.getY()); line.setColor(Color.MAGENTA); add(line); thisPeg = nextPeg; } }
page 1 of 2
skip code
The pegIndex++ expression adds one to pegIndex just as if has all along. The question is what value is used as the index, which depends on where the ++ operator appears:
If the ++ operator comes after a variable, the variable is incremented after the value of the expression is determined. Thus, in this example, the expression pegs[pegIndex++] therefore selects the element of the array at the current value of pegIndex and then adds one to pegIndex afterwards, which moves it on to the next index position. If the ++ operator comes before a variable, the variable is incremented first and the new value is used in the surrounding context.
The -- operator behaves similarly but subtracts one from the variable instead.
The variable scores is allocated on the stack and is assigned the address of a newly allocated array in the heap:
heap
1000
stack
1004 1008 1010 1018 1020 1028
0.0 0.0
scores
1000
FFFC
0, 1, 2, 3, 4, 5, 6, 7, 8, 0 1 2 3 4 5 6 7 8 9
10 9 8 7 6 5 4 3 2 1 0
9 0
0
1 0 8
1
2 0 7
2
3 6 0
3
4 5 0
4
5 0 4
5
6 0 3
6
7 0 2
7
8 0 1
8
9 0
9
ReverseArray
Cryptograms
A cryptogram is a puzzle in which a message is encoded by replacing each letter in the original text with some other letter. The substitution pattern remains the same throughout the message. Your job in solving a cryptogram is to figure out this correspondence.
One of the most famous cryptograms was written by Edgar Allan Poe in his short story The Gold Bug.
In this story, Poe describes the technique of assuming that the most common letters in the coded message correspond to the most common letters in English, which are E, T, A, O, I, N, S, H, R, D, L, and U.
Edgar Allan Poe (1809-1849)
AGOODGLASSINTHEBISHOPSHOSTELINTHEDEV 53305))6*;4826)4)4);806*;488 ILSSEATFORTYONEDEGREESANDTHIRTEENMIN 60))85;1(;:*883(88)5*;46(;88*96* UTESNORTHEASTANDBYNORTHMAINBRANCHSEV ?;8)*(;485);5*2:*(;4956*2(5*4)8 ENTHLIMBEASTSIDESHOOTFROMTHELEFTEYEO 8*;4069285);)68)4;1(9;48081;8:8 FTHEDEATHSHEADABEELINEFROMTHETREETHR 1;4885;4)485528806*81(9;48;(88;4( OUGHTHESHOTFIFTYFEETOUT ?34;48)4;161;:188;?;
Implementation Strategy
The basic idea behind the program to count letter frequencies is to use an array with 26 elements to keep track of how many times each letter appears. As the program reads the text, it increments the array element that corresponds to each letter.
T WA S BRI L L I G
1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 1 2 1 1 1 1 1
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
CountLetterFrequencies
import acm.program.*; /** * This program creates a table of the letter frequencies in a * paragraph of input text terminated by a blank line. */ public class CountLetterFrequencies extends ConsoleProgram { public void run() { println("This program counts letter frequencies."); println("Enter a blank line to indicate the end of the text."); initFrequencyTable(); while (true) { String line = readLine(); if (line.length() == 0) break; countLetterFrequencies(line); } printFrequencyTable(); }
/* Initializes the frequency table to contain zeros */ private void initFrequencyTable() { frequencyTable = new int[26]; for (int i = 0; i < 26; i++) { frequencyTable[i] = 0; } }
page 1 of 2 skip code
CountLetterFrequencies
import acm.program.*; /* Counts the letter frequencies in a line of text */ private void countLetterFrequencies(String line) { /** for (int i = 0; i < line.length(); i++) { * This program creates a table of the letter frequencies in a char ch = line.charAt(i); * paragraph of input text terminated by a blank line. if (Character.isLetter(ch)) { */ int index = Character.toUpperCase(ch) - 'A'; public class CountLetterFrequencies extends ConsoleProgram { frequencyTable[index]++; public} void run() { println("This program counts letter frequencies."); } } println("Enter a blank line to indicate the end of the text."); initFrequencyTable(); while (true) { /* Displays the frequency table */ String line = readLine(); private void printFrequencyTable() { for if (line.length()ch <= 'Z'; ch++) { (char ch = 'A'; == 0) break; countLetterFrequencies(line); int index = ch - 'A'; } println(ch + ": " + frequencyTable[index]); printFrequencyTable(); } } }
/* Initializes the variables */ /* Private instance frequency table to contain zeros */ private void frequencyTable; private int[] initFrequencyTable() { frequencyTable = new int[26]; for (int i = 0; i < 26; i++) { } frequencyTable[i] = 0; } }
page 2 of 2 skip code
The End