Download ARRay and more Lecture notes Computer Engineering and Programming in PDF only on Docsity!
Simple Arrays
Introduction to Arrays
- (^) An array is a collection of individual data values with two
distinguishing characteristics:
- (^) 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.
An array is ordered. You must be able to count off the values:
here is the first, here is the second, and so on.
An array is homogeneous. Every value in the array must have
the same type.
An Example of Array Declaration
- (^) The following declaration creates an array called intArray
consisting of 10 values of type int:
int[] intArray = new int[10];
- (^) 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:
0 1 2 3 4 5 6 7 8
9
intArray
- (^) 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.
0 1 2 3 4 5 6 7 8
9
intArray
- (^) 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;
* 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;
Exercise: Summing an Array
Write a method sumArray that takes an array of integers and
returns the sum of those values.
Human-Readable Index Values
- (^) From time to time, the fact that Java starts index numbering at
0 can be confusing. In particular, if you are interacting with a
user who may not be Java-literate, it often makes more sense
to let the user work with index numbers that begin with 1.
- (^) There are two standard approaches for shifting between Java
and human-readable index numbers:
Use Java’s index numbers internally and then add one
whenever those numbers are presented to the user.
Use index values beginning at 1 and ignore element 0 in
each array. This strategy requires allocating an additional
element for each array but has the advantage that the
internal and external index numbers correspond.
Passing Arrays as Parameters
- (^) When you pass an array as a parameter to a method or return
a method as a result, only the reference to the array is actually
passed between the methods.
- (^) The effect of Java’s strategy for representing arrays internally
is that the elements of an array are effectively shared between
the caller and callee. If a method changes an element of an
array passed as a parameter, that change will persist after the
method returns.
- (^) The next slide contains a simulated version of a program that
performs the following actions:
1. Generates an array containing the integers 0 to N - 1.
2. Prints out the elements in the array.
3. Reverses the elements in the array.
4. Prints out the reversed array on the console.
The ReverseArray Program
skip simulation
public void run() {
int n = readInt("Enter number of elements: ");
int[] intArray = createIndexArray(n);
println("Forward: " + arrayToString(intArray));
reverseArray(intArray);
println("Reverse: " + arrayToString(intArray));
} n
intArray
ReverseArray Enter number of elements: 10 Forward: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Reverse: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
private int[] createIndexArray(int n) {
int[] array = new int[n];
for ( int i = 0; i < n; i++ ) {
array[i] = i;
return array;
i n array
0 1 2 3 4 5 6 7 8
9
private String arrayToString(int[] array) {
String str = "";
for (int i = 0; i < array.length; i++) {
if (i > 0) str += ", ";
str += array[i];
return "[" + str + "]";
str i array
private void reverseArray(int[] array) {
for (int i = 0; i < array.length / 2; i++) {
swapElements(array, i, array.length - i - 1);
i array
private void swapElements(int[] array, int p1, int p2) {
int temp = array[p1];
array[p1] = array[p2];
array[p2] = temp;
array
p
temp p
public void run() {
int n = readInt("Enter number of elements: ");
int[] intArray = createIndexArray(n);
println("Forward: " + arrayToString(intArray));
reverseArray(intArray);
println("Reverse: " + arrayToString(intArray));
} n^ intArray
0 1 2 3 4 5 6 7 8
9
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.
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
TWAS BRILLI G
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
Initializing Arrays
- (^) Java makes it easy to initialize the elements of an array as
part of a declaration. The syntax is
type [] name = { elements };
where elements is a list of the elements of the array separated
by commas. The length of the array is automatically set to be
the number of values in the list.
- (^) For example, the following declaration initializes the variable
powersOfTen to the values 10
0
1
2
3
, and 10
4
int[] powersOfTen = { 1, 10, 100, 1000, 10000 };
This declaration creates an integer array of length 5 and
initializes the elements as specified.
Arrays and Graphics
- (^) Arrays turn up frequently in graphical programming. Any
time that you have repeated collections of similar objects, an
array provides a convenient structure for storing them.
- (^) As an aesthetically pleasing illustration of both the use of
arrays and the possibility of creating dynamic pictures using
nothing but straight lines, the text presents the YarnPattern
program, which simulates the following process:
- (^) Place a set of pegs at regular intervals around a rectangular border.
- (^) Tie a piece of colored yarn around the peg in the upper left corner.
- (^) Loop that yarn around the peg a certain distance DELTA ahead.
- (^) Continue moving forward DELTA pegs until you close the loop.
import acm.graphics.; import acm.program.; import java.awt.; /*
- 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(pegs); 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; } }
The YarnPattern Program
page 1 of 2 skip code
import acm.graphics.; import acm.program.; import java.awt.; /*
- 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; } } / Initializes the array of pegs / private void initPegArray() { int pegIndex = 0; for (int i = 0; i < N_ACROSS; i++) { pegs[pegIndex++] = new GPoint(i * PEG_SEP, 0); } for (int i = 0; i < N_DOWN; i++) { pegs[pegIndex++] = new GPoint(N_ACROSS * PEG_SEP, i * PEG_SEP); } for (int i = N_ACROSS; i > 0; i--) { pegs[pegIndex++] = new GPoint(i * PEG_SEP, N_DOWN * PEG_SEP); } for (int i = N_DOWN; i > 0; i--) { pegs[pegIndex++] = new GPoint(0, i * PEG_SEP); } } / Private constants / private static final int DELTA = 67; / How many pegs to advance / private static final int PEG_SEP = 10; / Pixels separating each peg / private static final int N_ACROSS = 50; / Pegs across (minus a corner) / private static final int N_DOWN = 30; / Pegs down (minus a corner) / private static final int N_PEGS = 2 * N_ACROSS + 2 * N_DOWN; / Private instance variables */ private GPoint[] pegs = new GPoint[N_PEGS]; }
The YarnPattern Program
page 2 of 2