Chapter 8: Arrays Motivation - PowerPoint PPT Presentation

1 / 50
About This Presentation
Title:

Chapter 8: Arrays Motivation

Description:

Standard deviation can be thought of as an average distance that each number is ... sometimes referred to as a conglomeration variable or as a collection variable ... – PowerPoint PPT presentation

Number of Views:106
Avg rating:3.0/5.0
Slides: 51
Provided by: foxr
Category:

less

Transcript and Presenter's Notes

Title: Chapter 8: Arrays Motivation


1
Chapter 8 Arrays Motivation
  • Assume that you want to compute the standard
    deviation of a list of numbers
  • Standard deviation can be thought of as an
    average distance that each number is from the
    average
  • The formula is Sqrt( (ai avg)2) / n
  • ai is each number
  • avg is the average (previously computed)
  • n is the number of numbers
  • One problem if we use a loop to perform this
    task, we need to input all n numbers to calculate
    the avg, how then do we go back and compute the
    sum of each (ai avg)2?
  • We either need to repeat the process of asking
    the user to input each number, or we need to
    remember each number

2
Remembering the Numbers
  • Recall that in our previous implementation of
    computing an average, we used a loop whereby we
    inputted each number, added it to a running
    total, and repeated

while (more) System.out.print("Enter
a number ") value Integer.parseInt(key
.readLine( )) count count 1
sum value System.out.print("Is there
another number? ") answer key.readLine(
) if (answer.equals("yes")) more true
else more false
During each new iteration, we discard the last
value, so how can we remember all of them?
3
A Bad Solution
  • We could use different variables, one for each
    input
  • Example
  • int num1, num2, num3, num4, , num1000
  • System.out.print("Enter first number ")
  • num1 Integer.parseInt(key.readLine( ))
  • System.out.print("Enter second number ")
  • num2 Integer.parseInt(key.readLine( ))
  • System.out.print("Enter the thousandth number
    ")
  • num1000 Integer.parseInt(key.readLine( ))
  • double average (double) (num1 num1000) /
    1000
  • double sd Math.sqrt(Math.pow(num1 average),
    2) Math.pow(num2 average), 2)
    (Math.pow(num1000 average), 2) / n
  • Why is this a bad solution?
  • Will it work if we only want to average 999
    numbers?
  • What about 1001 numbers?
  • How long will it take you to type up this program
    given that you have to have 1000 input statements?

4
Arrays
  • The idea behind our solution was right, but the
    implementation was flawed
  • We need to store all of the input values
  • What we dont want to do is
  • Make the programmer work extra hard to do this
  • Plus we want the flexibility whereby the number
    of values can vary
  • An array is sometimes referred to as a
    conglomeration variable or as a collection
    variable it can store more than one value, in
    fact, it can store as many values as we want it
    to
  • We treat the array as a single entity that
    consists of parts and fill in those parts as
    needed
  • We refer to the array by one name but we also
    refer to which part of the array that we are
    interested in

5
An Example of an Array
Here is an array of numbers The array is
called scores The array stores individual int
values (10 of them) We can refer to the
entire array as scores, we can refer to
individual values by indexing them
6
Referencing Array Values
  • We must refer to the value we are interested in
    when using an array
  • The reference is nameitem where name is the
    array name (the variables name) and item is the
    location of the item within the array
  • item will be a number between 0 and n-1 where n
    is the number of array items stored
  • We start at 0 because this is how C and C were
    implemented, many languages actually have array
    indexes between 1 and n instead
  • Example from the scores array, the first item
    is scores0, the last item is scores9

7
Some Array Examples
Input into an array Select a random number and
store in an array Compute the average of
3 array values Compute the sum of previous array
values storing in another array location
scores5 Integer.parseInt(key.readLine( ))
value9 (int) Math.random() 100 average
(number1 number2 number3) / 3
test3 test0 test1 test2
8
Accessing an Entire Array
  • Accessing an array can become cumbersome if we
    are going to refer to each item in a separate
    instructions or as a separate reference in an
    instruction
  • We instead will often reference a particular
    array item from within a loop where the reference
    changes based on the loop iteration

for(i0ilt100i)
System.out.print("Enter value " i " ")
numi Integer.parseInt(keyb.readLine(
))
Input 100 items, storing them in the array
num Much easier than having 100 prompt and 100
input statements!
Loop index i is also used as the array index
9
Computing Average and Standard Deviation
int sum 0 double sum2 0
System.out.println("How many values do you have?
") int n Integer.parseInt(keyb.readLine( ))
for(j0jltnj) System.out.println("Enter
value " j " ") numj
Integer.parseInt(keyb.ReadLine()) sum
numj double average (double) sum /
n for(j0jltnj) sum2 Math.pow((double)
numj average), 2) double sd (double) sum2
/ n
Input into the array at numj, and use this
value to add to the running total Compute the
average Compute the standard deviation by
accessing each array item again
10
Declaring Arrays
  • As with all variables in Java, declaring arrays
    requires stating the type followed by the
    variable name
  • However, to denote an array, we follow the type
    with marks as in
  • int x
  • We can also place the marks after the
    variable name as in
  • int x
  • While the book uses this latter approach, it is
    more common in Java to use the earlier approach
  • Notice though that if you want to declare two
    array variables, one an array and one a single
    value, you would have to do it as
  • int x , a // here x is an array, a is an int
  • And not
  • int x, a // here, both x and a are arrays

11
Arrays are Objects Not Primitives
  • However, the individual array element is the type
    that the array was declared to store and so
    individual array elements can be primitives
  • Example
  • int x means that x is an array, or x is a
    reference variable that points to the array where
    each element of the array is an int
  • As a result of this, the array must be
    instantiated before it can be used
  • Instantiating follows this form
  • name new typesize
  • And so can be combined with the declaration such
    as
  • int x new int10
  • Or
  • int x new int10

12
Example
double prices creates prices
new double6 creates Notice that the
array values are initialized to 0.0
13
String Arrays
  • What happens if we want to have an array of
    Strings?
  • The array of Strings is an array of objects
  • Recall that all objects are pointed to by
    reference pointers
  • So in fact, the array of Strings is an array of
    reference pointers, each of which point to a
    String

String names new String4 creates this
array structure
Names after each individual String has been
assigned a value
14
Initializing Arrays
  • When declaring an array, we can also provide it
    with its initial values if we desire
  • Initializing is done by placing a list of values
    after the name in symbols where each value is
    separated by commas
  • Example int scores 87, 98, 69, 54, 65,
    76
  • This array is automatically initialized with 6
    values stored in scores0 scores5
  • Note that since we did not issue a new command or
    provide an upper limit, this array can only store
    6 items although we could change their values
  • Example char letterGrades A, B, C,
    D, F
  • Example String names "Frank", "Fred",
    "Hank", "Jed"
  • We will only use array initialization if we
    already know what values will go into the array
  • We may choose to use array initializations if we
    want to create a group constant such as the
    legal letter grades

15
Array Length
  • Imagine that we want to output all elements in an
    array
  • We can use a for-loop to iterate through each
    element and output each as follows
  • for(j0 jltn j) System.out.println(namej)
  • The problem with this solution is, what is n?
  • How many elements are stored in the array?
  • How do we keep track of this?
  • Later on, we will see how we can do this
  • One solution is to use the array length operation
  • name.length is the size of the array
  • somewhat like Strings length method
  • Notice, unlike the String length( ), length does
    not have an empty parameter list
  • this is because length is not a method, but
    instead a datum stored with the array itself

16
Copying Arrays
  • Recall that x y differs if x and y are
    primitive types or objects
  • If x and y are ints, then the value of y is
    copied into x
  • If x and y are Strings, then x and y will now
    point at the same String
  • This is also true of arrays
  • Consider the following code
  • To get around this problem, known as a shallow
    copy, we must make a deep copy of y into x

int x, y y new array4 y0 3 y1
9 y2 0 y3 4 x y // at this
point, x and y point at the same array
17
Making a Shallow Copy
Consider the following Operations int
nums, newnums nums new int5
newnums new int5 nums0
nums1 nums4
newnums nums this last operation creates
the situation shown to the left where newnums now
points to the same array as nums
The danger of a shallow copy is that if you
change newnumsj it is the same as changing
numsj and this can be dangerous if you are not
expecting nums to change!
18
Making A Deep Copy
  • One way to make a deep copy is to copy each
    element of the second array into the first as
    shown below
  • Java also offers the System.arraycopy method
    which does the same thing

x new inty.length for(j 0 j lt y.length
j) xj yj
  • System.arraycopy(y, 0, x, 0, y.length)
  • The parameters for arraycopy are as follows
  • source array (array copied from)
  • starting location in source array (what is the
    first element to be copied)
  • destination array (array copied to)
  • starting location in destination array
  • number of elements to be copied

19
Array Example
import java.io. public class ArrayExample
public static void main(String args)
throws IOException
BufferedReader key new BufferedReader(new
InputStreamReader(System.in))
System.out.print("How many test scores do you
want to average? ") int number
Integer.parseInt(key.readLine( )) int
scores new intnumber for(int j
0 j lt number j)
System.out.print(Enter score " j " " )
scoresj Integer.parseInt(key.rea
dLine( )) sum scoresj
double average (double) sum
/ number System.out.println("Your
test scores are") for(int j 0 j lt
number j) System.out.println(
scoresj) System.out.println("And
the average score out of " number " scores is
" average)
20
Array Length Revisited
  • In our previous example we asked the user how
    many elements were going to be stored in the
    array
  • We then used that value (number) to instantiate
    the array and control the for loops (for input,
    for sum, and for output)
  • What if the user does not know at the beginning
    of the program the number of values to be
    entered?
  • Remember earlier we used arrays length operator
    but that value is the size of the array
  • It will not necessarily be the number of elements
    in the array
  • A common approach is to use a query-controlled or
    sentinel loop for input and count the number of
    iterations
  • the number of iterations is the number of inputs
    and so it tells us the number of elements
    currently stored in the array
  • This may be necessary because we cannot assume
    that all array positions are actually being used
  • array.length only tells us the size of the array,
    not where the last element is stored in the array

21
Example Inputting and Counting
import java.io. public class
CountArrayElements public static void
main(String args)
BufferedReader key new BufferedReader(new
InputStreamReader(System.in)) int
list new int100 // assume array wont store
more than 100 items int number 0
System.out.print("Enter a positive number
to add to your list ") int value
Integer.parseInt(key.readLine( ))
while(value gt 0 number lt 100)
listnumber value number System.out.pri
nt("Enter a positive number to add to your list
") int value Integer.parseInt(key.re
adLine( ))
System.out.println("Your list of numbers is")
for(int j 0 j lt number j)
System.out.println(listj)
Why are there two conditions here?
22
Passing Arrays as Parameters
  • We now want to develop a program that
  • Inputs an array
  • Computes the arrays sum/average/standard
    deviation
  • Outputs the array
  • Etc
  • In order to write our program reasonably, we will
    divide these operations into methods
  • So, we must pass the array as a parameter from
    the main method to each individual method
  • How?
  • If we had to pass each array element, it would be
    difficult, but the array as a whole can be passed
    as a single variable
  • The actual parameter is just the array name
  • The formal parameter is the array type followed
    by the name it will receive in the method such as
    (int a)

23
More on Passing Arrays
  • Not only do we pass the array
  • we should also pass the number of elements in the
    array
  • in this way, the receiving method knows how many
    elements to iterate through in its own loops
  • What happens if an array element is changed in
    the method?
  • This change will be reflected upon returning from
    the method call because the array in the actual
    parameter list points to the actual array object
    in memory and so the array in the formal
    parameter list is the same array
  • How can we input an array and return it if a
    method only returns 1 value?
  • The value returned is the reference variable,
    pointing to the array
  • Examples of these ideas follow

24
Example Passing Array and Array Size
public static void main(String args)
int list new list100 int number
code to input array list
System.out.println("The sum of the array is "
sum(list, number)) System.out.println("The
average of the array is " average(list,
number)) System.out.println("The standard
deviation of the array is " sd(list, number))
public static int sum(int x, int n)
int sum 0 for(int j0 j lt n j) sum
xj return sum public static
double average(int x, int n) double
temp (double) sum(x, n) / n return
temp
  • This partial class calls methods to compute sum,
    average, and standard deviation (omitted to save
    space)
  • Notice how average calls the sum method
  • Similarly sd would call the average method

Both the array and the number of data stored in
the array are being passed as parameters
25
Example Inputting the Array in a Method
import java.io. public class ArrayExample
public static void main(String args)
throws IOException int list
list inputArray( )
outputArray(list) public static int
inputArray( ) throws IOException
BufferedReader key new BufferedReader(new
InputStreamReader(System.in)) int
temp new int100 int number 0
input the array here return
temp public static void
outputArray(int x) for(int
j0 jltx.length j) System.out.println(xj)

Notice that we are not returning the size of the
array, and so we cannot pass this value on to
outputArray to be used here What can we
do about this?
26
Changing Values in a Method
int values new int100 int number
code to input values here changeArray(values,
number, 99) public static void
changeArray(int a, int n, int x)
for(int j 0 j lt n j) if(aj gt
x) aj--
  • The code here seeks out all int values in the
    array gt x and reduces them by 1
  • What affect does this have on the original array?

values (before changeArray) a in changeArray (a
and values are the same array) values (after
changeArray)
27
Operations on an Array
  • The array is often used to represent a list of
    values
  • What do we do with a list?
  • If its a list of numbers, we might want to know
    the sum, average, standard deviation, find the
    maximum or minimum items in the list
  • If it is a list of Strings, we might want to find
    the maximum or minimum, or we might want to find
    if a certain String exists in the list
  • Does the name Frank Zappa appear?
  • If found, we might want to change it, delete it
    or return its location
  • Or, we might want to find a particular element in
    the list (this is known as searching the list)
  • We might also want to sort the list (of names or
    numbers) to appear in ascending or descending
    order
  • We might want to also add a new element to an
    array or delete an element from an array

28
How Do We Find the Minimum/Maximum?
  • Consider holding a list of names on 3x5 cards
  • You are to find the name earliest alphabetically
    (the minimum)
  • look at the first card
  • this name is so far the earliest alphabetically
  • since its the only one youve looked at
  • look at the second card and compare that name to
    the earliest
  • if the new name is earlier, you can remember the
    new name and thus forget the hold name,
    otherwise, continue to remember the other
  • go onto the third card,
  • continue until you have reached the last card
  • The name you remember is the earliest
  • This strategy will work whether you are trying to
    find the first or last alphabetical name, or the
    minimum or maximum value in a list of numbers
  • The process will require a for-loop with an if
    statement

29
Examples Minimum/Maximum
public static int findMax(int x, int n)
int max x0 for(int j 1 j lt n
j) if(xj gt max) max xj
return max public static String
findEarliest(String names, int n)
String earliest names0 for(int j 1
j lt n j) if(namesj.compareTo(earli
est) lt 0) earliest namesj return
earliest
Here we have two examples to find the maximum int
in an array and to find the earliest
(minimum) String in a different array Notice
that we store the min/max as the first array
element (element 0) and then start looking at
each successive element For Strings, we must use
compareTo since lt and gt do not work
30
Example Searching
public static int find(String names, int n,
String target) int returnLocation -1
for(int j 0 j lt n j)
if(namesj.equals(target)) returnLocation j
return returnLocation
We could change this to be a count
occurrences method that counts the number of
times target appears by initializing
returnLocation to 0 and adding 1 to it every
time namesj equals target
This method is passed an array of Strings and the
number of Strings stored there And a target
that is, a String to search for It searches for
the String and if it finds it, it returns its
location in the array If target is not found,
what value is returned? If target appears more
than once in the array, what value is returned?
If we want the earliest occurrence of target,
how could we change this code? Note if we do
change the code, we can make the method more
efficient!
31
Example Adding
  • Assume that we already have an array with number
    items in it
  • We want to add a new item
  • How?
  • If there is room, input the new item and add it
    at the end of the array

public static void add(int x, int number, int
newValue) if(number lt x.length)
xnumber newValue
number else
System.out.println("Cannot add " newValue
"since array is full")
Adding 19, with number 8 and length 12, 19
gets added at position 8 and number becomes 9
19
32
Deleting an Element
  • To delete an item from an array, we must first
    find it
  • We have already seen code to find an item and
    return its location so that part is easy
  • How do we physically remove it?
  • If it is an array of String values
  • we can set the given array element to null which
    removes the String
  • If it is an array of int values
  • we could set that array element to 0 or some
    special value like 9999
  • The problem is that these solutions leave a
    hole in the array
  • For instance, if we want to delete the element at
    list5, then the next time we print the list,
    this item is not a true value, but instead, a
    null value this may also cause problems when
    searching
  • We will instead replace the deleted element with
    the last element of the array and then subtract 1
    from number
  • This corresponds to covering up the last element
    such that it will never be accessed again

33
Example Deleting
public static void delete(int x, int number,
int target) int location find(x,
number, target) if(location ! -1)
xlocation xnumber - 1 number--
else System.out.println("Cannot delete "
target " not found in the array!")
Notice that if target is found, we first move the
last item in the array (which is at location
number 1) into the location of the item to be
deleted, we then subtract 1 from number to
indicate 1 fewer item in the array Below, assume
we want to delete11, once found (at location 4),
we move the last item (at location number or 9)
into its place and subtract 1 making number 8
number 9 number 8
34
Command-Line Arguments
  • To this point, when defining the main method of
    our programs, we have ignored the parameters
  • public static main(String args)
  • Now we can try to understand what these are
  • When we execute our Java program, we are
    essentially calling the main method of our class
  • If we just invoke it, then we are passing no
    parameters and so args0 has no value
  • However, we could also invoke our main method
    with parameters such as
  • java ExecuteExample hello goodbye and thanks
  • In this case, args0 hello, args1
    goodbye, args2 and and args3 thanks
  • We wont use this in class, but you might have
    been curious

35
Sorting
  • Given an array how do you sort them to be in
    order?
  • Consider taking a stack of exams and sorting them
    in alphabetic order by the students name, or in
    numerical descending order by grade
  • You might search the whole stack to find the
    highest score (or earliest name) and move it to
    the front, then repeat until all have been sorted
    this is a process known as selection sort
  • You might take the second exam and insert it
    either before or after the first, then take the
    third and insert it into its appropriate place
    (before first, between first and second, after
    second) and repeat until all have been sorted
    this process is known as the insertion sort
  • There are many different sorting algorithms, this
    is a popular topic in Computer Science
  • we will examine the Selection and Insertion sorts
    here as they are two of the simplest

36
Selection Sort
  • The basic idea of the selection sort is to start
    at array location 0 and swap that value with the
    largest (or smallest) in the array
  • Recall that we saw in chapter 3 how to search a
    list of values for the largest or smallest
  • Then, we do the same starting at location 1
  • We repeat until we have reached the end of the
    array

Position 0 1 2 3 4 original
3 9 6 1 2 smallest is 1 1 9
6 3 2 (swap with position 0) smallest is
2 1 2 6 3 9 (swap with position 1)
smallest is 3 1 2 3 6 9 (swap with
position 2) smallest is 6 1 2 3 6 9
(swap with position 3) finished when we reach
position 4
37
Selection Sort Implemented
  • Given an array with elements 0..n-1
  • Start at position 0 and find the smallest value
    from 0..n-1 and swap with value at position 0
  • Start at position 1 and find the smallest value
    from 1..n-1 and swap with value at position 1
  • Start at position 2 and find the smallest value
    from 2..n-1 and swap with value at position 2
  • Start at position n-2 and find the smallest value
    from n-2 to n-1 and swap with value at position
    n-2

for(j0jltn-1j) smallest aj
location j for(kj1kltnk)
if (ak lt aj)
smallest ak
location k temp
aj aj alocation
alocation temp
38
Another Example
Position 0 1 2 3 4 5
6 Original Array 8 12 3 16 5
19 9 1st pass 3 12 8 16 5 19
9 3 is smallest, swap with 8 2nd
pass 3 5 8 16 12
19 9 5 is smallest, swap with 12 3rd
pass 3 5 8 16 12
19 9 8 is smallest, swap with 8 4th
pass 3 5 8 9 12
19 16 9 is smallest, swap with 16 5th
pass 3 5 8 9 12
19 16 12 is smallest, swap with 12 6th
pass 3 5 8 9 12
16 19 16 is smallest, swap with 19
This algorithm requires n-1 passes of an array of
size n This example has an array of 7 values, it
took 6 passes to sort the array
39
Insertion Sort
  • The selection sort made numerous passes over a
    shrinking portion of the array
  • The insertion sort works virtually in the
    opposite direction, by taking the next item in
    the array and inserting it into the already
    sorted portion
  • The item at location 0 is already sorted with
    respect to itself, so we start at location 1 and
    see how to insert it into an array with 1 item
  • Then insert the item in location 2 into an array
    of 2 items
  • Then insert the item in location 3 into an array
    of 3 items, and continue until the item at
    location n-1 has been inserted

original 3 9 6 1 2 insert 9
3 9 6 1 2 insert 6 3 6 9
1 2 insert 1 1 3 6 9 2
insert 2 1 2 3 6 9 Start with
3, insert 9 giving 3 9 Next,
insert 6 giving us 3 6 9 Next,
insert 1 giving us 1 3 6 9
Finally insert 2 giving us 1 2 3 6
9
40
How the Insertion Sort Works
  • Unlike the Selection Sort which just required
    going down the array remembering the smallest (or
    largest) item and its location and then swapping
    the two values, we have more to do here
  • To insert the item at position i, go down the
    list from 0 to i-1 and find the right location,
    say j
  • Shift items from j to i-1 down 1 position to the
    right
  • Insert the item at position i into the newly
    freed up position j

2) Shift elements down
  • Move ith item into
  • open location

1 6 8 12 19 23 28 33 15 7
20
1) Search for proper location to insert
41
To Simplify Our Task
  • Do for each value from 1 to n-1
  • Store the ith value in a temporary location
  • Repeat
  • If value at i-1 gt ith value, shift i-1 down to i
  • Until we have found a value lt the ith value or we
    have reached the beginning of the array
  • Thus, we shift while we search, saving us some
    work

for(j1 jltn j) current aj
position j while(position gt 0
aposition-1 gt current)
aposition aposition-1
position--
aposition current
42
Another Example
Position 0 1 2 3 4 5
6 Original Array 8 12 3 16 5
19 9 1st pass 8 12 3 16 5 19
9 8 and 12 in correct order 2nd pass
3 8 12 16 5 19 9
Insert 3 with 8 12 3rd pass
3 8 12 16 5 19 9 16
in right order w/ 3, 8, 12 4th pass
3 5 8 12 16 19 9
Insert 5 between 3 and 8 5th pass
3 5 8 12 16 19 9 19 in
right order with rest 6th pass 3
5 8 9 12 16 19 Insert
16, done
As with Selection Sort, Insertion Sort requires
n-1 passes of an array of size n This example
has an array of 7 values, it took 6 passes to
sort the array
43
Sorting Different Types
  • In our examples, we sorted integers
  • We could just as easily have sorted an array of
    floats or doubles or chars because lt and gt work
    on any of these types
  • What about Strings?
  • We would have to modify our algorithm to use
    compareTo
  • For Selection Sort
  • if(aj lt ak) becomes
  • if(aj.compareTo(ak) lt 0)
  • For Insertion Sort
  • while(position gt 0 aj gt current) becomes
  • while(position gt 0 aj.compareTo(current) gt 0)

44
Comparing Sorts
  • Aside from Selection and Insertion Sorts, there
    are Bubble, Merge, Quick and Radix Sort
  • Why so many? How do you choose one?
  • Selection Sort has a peculiar performance, no
    matter whether the array is already sorted,
    mostly sorted, or completely unsorted, it takes
    approximately n(n-1) comparisons to sort the
    array
  • Insertion Sort might perform better if the array
    is already close to sorted, same with Bubble Sort
  • These three sorts have a worst case complexity
    known as O(n2) (takes approximately n2
    comparisons to sort an array of n items)
  • But Bubble and Insertion Sort might perform
    better if the array is partially or close to
    completely sorted
  • Turns out that Merge and Quick Sort are even
    better, their performance is usually around O(n
    log n)
  • These are ideas that we explore in more detail in
    later CS courses

45
Two-Dimensional Arrays
  • To this point, all of our arrays have been
    one-dimensional
  • They have been indexed by a single value
  • Such an array stores a list of items where each
    item has one predecessor and one successor
  • Applications for one-dimensional arrays are often
    based on storing lists of values
  • Applications for two-dimensional arrays are often
    based on storing tables with rows and columns
  • Spreadsheet
  • Mileage table
  • Chess board
  • Two-dimensional arrays are much like
    one-dimensional arrays but have two indices
    instead of one

46
Declaring and Using 2-D Arrays
  • The only real difference between 1-D and 2-D
    arrays is that the 2-D array requires two indices
    instead of 1
  • We specify the indices in separate s as in
    aij
  • We declare 2-D arrays by having two sets of s
  • int a new int1010
  • Legal array indexes for a are from 0..9 and 0..9
    such as a00, a51, a39 and a99
  • We will commonly use 2 nested for-loops to
    iterate through a 2-D array

int a new1010 for(i0ilt10i)
for(j0jlt10j) aij 0
47
2-D Array Applications
  • Mileage Chart
  • Given a list of cities and the miles between each
    pair of cities, the distance between i and j is
    stored at mileageij
  • In this case, mileageij mileageji and
    mileagejj 0
  • Game Board
  • For instance, a Chess board would be an 8x8 board
    where each entry stores a String representing a
    piece
  • chess00 White Rook, chess53
    Empty, etc
  • Multiplication Table

int multTable multTable new
int1010 for(i0ilt10i)
for(j0jlt10j) multTableij i
j for(j0jlt10j) System.out.print(j
" ") System.out.println() for(i0ilt10i)
System.out.print(i " ")
for(j0jlt10j) System.out.print
(multTableij " ")
System.out.println()
48
Multi-Dimensional Arrays
  • In Java (as well as many other languages), there
    is no limit to the number of dimensions of an
    array
  • A 3-D array requires 3 indices, we might think of
    them as being row, column and level or height,
    width and depth
  • A 3-D array might be used to represent objects in
    space
  • A 4-D array is much harder to visualize
  • Arrays beyond 4 dimensions are sometimes used but
    not very commonly
  • For a 3-D array, we would most likely use 3
    nested for-loops to perform operations on it
  • Declaring a multi-dimensional array is like
    declaring a 2-D array
  • int threeDArray new int100100100
  • int fiveDArray new
    int51051020

49
Initializing Multi-dimensional Arrays
  • As with one-dimensional arrays, any
    multi-dimensional array can be initialized at the
    time it is created
  • int a 5, 3, 1, 4, 2, 0, 6, 8, 10,
    0, 1, 9
  • Creates an array of 4 rows and 3 columns where
    a00 5, a01 3, a02 1, a10
    4, a11 2, a12 0, a20 6, a21
    8, etc
  • Note that declaring an array this way does not
    restrict the array having an equal number of
    items per row
  • On page 326, there is an example where the 2-D
    array has 3 rows with 3, 2 and 4 items
    respectively
  • The book covers multi-dimensional array
    initialization more detail than we need, so we
    will skip the rest of section 8.4, but you might
    want to read it for your own education

50
Common Errors
  • Forgetting the when referencing an array
  • Forgetting to instantiate a declared array
  • Off-by-one
  • forgetting that arrays start at 0 and go to
    length 1
  • Going beyond the last item stored in the array
    because you are relying on the array length
    operator
  • Similarly, creating an array that is too small in
    size so that you run out of space, or inputting
    into a full array such that your array index goes
    beyond the legal bounds
  • Forgetting to save/pass the number of items in
    the array
  • Altering an array in a method unintentionally
  • Using a value other than an int as an array index
Write a Comment
User Comments (0)
About PowerShow.com