Chapter 6- Arrays - PowerPoint PPT Presentation

About This Presentation
Title:

Chapter 6- Arrays

Description:

If you don't give an initialization list to an array, the computer just ... A binary search can be performed if all of the data is in order(like a phone book) ... – PowerPoint PPT presentation

Number of Views:20
Avg rating:3.0/5.0
Slides: 65
Provided by: erics84
Learn more at: https://www.cs.uaf.edu
Category:

less

Transcript and Presenter's Notes

Title: Chapter 6- Arrays


1
Chapter 6- Arrays
2
Overview
  • What are arrays?
  • Declaring/initializing arrays.
  • Using arrays.
  • Arrays details.
  • Using arrays with classes/ in classes.
  • Sorting/searching arrays.
  • Multidimensional arrays.
  • Review

3
Arrays, what are they?
4
What are arrays?
  • An array is a large collection of variables that
    are all of the same data type.
  • It allows us to have a large number of similar
    variables without having to declare each one
    individually.

5
What are arrays used for?
  • Think back to the grocery purchase program that
    we did. Imagine instead of having only five items
    (and declaring five Purchase objects) we had 100
    items the user could choose. Since much of the
    code for each Purchase object is similar, we
    could just have an array and one piece of code to
    repeatedly do stuff to that array.

6
More on arrays
  • Arrays are like mailboxes. They have a collective
    name (say the zip code for the University), an
    index (your box number), and a value (any mail in
    your box).

0
1
2
3
Index
Value
Value
43
105
Name
7
Arrays
  • Arrays are actually objects (though they dont
    look like it). They are initialized with the new
    operator. They store a memory address in their
    variable.
  • Weve already seen them, we just havent used
    them.

8
Declaring and initializing arrays
9
Declaring arrays.
  • We declare an array in a very similar way to how
    we declare variables. The only difference is the
    symbols.

int blar double 3 muglets String args
10
Initializing arrays.
  • There are lots of ways to initialize arrays.

blarnew int20 //blar now has 20 0s. muglets
new int2 //muglets now has 2
0s muglets02.3 muglets11.2 String
args Hello, How, are, you
11
Array indices
  • Arrays are indexed from 0 to (the length of the
    array 1). Remember this. It will cause you
    immeasurable grief in programming. The index
    always starts a 0.

blar new int20 //indexed 0-19 muglets new
double4 //indexed 0-3 args Howdy,
there //indexed 0-1 int lonely 1
//indexed 0-0
12
Declaring and initializing
  • Can declare and initialize arrays in just one
    statement(this is the usual way).

double muglet new double4 String words
Hello, Howdy int lonely 1
13
What is happening
int blar 1,7,4,6
0
1
2
3
blar
1
7
4
6
14
Which of the following are valid
declarations/initializations of arrays?
int arg new int(5) int arg new
int10 double blar blar new
double15 String muglet Hello char
yadda Howdy int someNum 1,5,7
Not valid
Not valid
Valid
Not valid
Not valid
Valid
15
What are the indices of the following arrays?
int arr new int10 double yadda new
double1 String hello Hello, Hello,
Hello int number 1,5,10,15,20 int I
4 double sum new doubleI
0-9
0-0
0-0
0-4
0-3
16
Using Arrays
17
Accessing arrays
  • To get at the information inside of an array, we
    again use the operators.
  • To access the ith element of an array called
    arrayName, we say arrayNamei.
  • Remember, we start at index 0, with the 0th
    element.

18
Using arrays
double someArray 1.4, 2.6,2.1,
3.4,8.4 double I someArray0//I1.4 double
j someArray1//j 2.6 double k
someArray2//k 2.1 double m
someArray3//m 3.4 double n
someArray4//n8.4 double o someArray5//o
ArrayIndexOutOfBounds Exception
19
More info on arrays.
  • The length of an array is also stored in the
    array object, and we can access it through the
    public length variable.
  • arrayName.length
  • We can only read this variable. We cannot set it.

20
Common uses of length.
//assume arr is an array. for(int I0
Iltarr.lengthI) System.out.println(arrI)
21
Which are valid uses of arrays?
int muglets new int5 double blar new
double3 muglets(0) 3 muglets3
24 muglets5 3 blar.length
muglets.length if(muglets.length
blar.length)
Not valid
Valid
Not valid
Not valid
Valid
22
Array Details
23
Some more rules about arrays.
  • All of a single array should be of the same type.
    You cant have a mixed array, part String and
    part integer. You can only store one type of data
    in a single array.
  • Array names are just memory addresses. Thus they
    act more like objects than primitives. You cant
    just use and to copy an array or compare
    arrays. Have to do it element by element.

24
More rules.
  • Dont go out of bounds! Stay within your array.
    You WILL make this mistake. Often. It WILL crash
    your program.
  • If you dont give an initialization list to an
    array, the computer just initializes all of the
    data in the array to some default value for the
    data type. If your data type is a class, it just
    stores null in the array position(you need to
    construct a new object when before you use
    this!).

25
Array details review
  • What is output to the screen?
  • int someArray new int5
  • someArray5 3
  • System.out.println(someArray5)
  • What does the name of the array store? What two
    common operations cant you do with arrays?

Nothing
26
Array Details Review
  • What is output to the screen?
  • int someArray new int20
  • System.out.println(someArray5)
  • Is the following valid?
  • int someArray new int20
  • someArray5 1

0
No
27
Using arrays with classes / in classes.
28
Using arrays in classes
  • We can use an array in any class that we want.
    They can be private instance variables. They can
    be public static variables. They can be variables
    that are local to a method.
  • We can also pass arrays to methods, return arrays
    from methods, or pass single elements from arrays
    to a method.

29
Using arrays in classes
private int blar //want to initialize
//in a constructor or //in some
method. public static double mug new
double15 private Purchase
itemsOffered
30
Passing single elements to a method
  • If a method requires a variable of the same data
    type as your array base type, then you can pass a
    single element to the method.
  • double blar 3.0,4.0
  • Triangle a new Triangle()
  • a.setBase(blar0) //a.setBase(3.0)
  • b.setHeight(blar1) //a.setHeight(4.0)

31
Passing arrays to methods
  • We can also pass whole arrays to methods(notice,
    every main method accepts a String array).
  • public void doSomething(int someArray)
  • int blar new int20
  • doSomething(blar)

Indicates it requires an array
Dont use array index things . Just the name.
If you use the symbols, you will pass a
single element, not the whole array.
32
Returning arrays from methods
  • We can also return arrays from methods, if we
    like. Be careful, this is just like returning a
    non-String object. If you want the array to be
    private, it is better to make a copy and return
    it.
  • public int doSomething()
  • int someArray new int20
  • return someArray

Indicates going to return an array.
Again, want to return the whole array, so we use
the whole name, no symbols.
33
Review - Arrays in classes and methods.
  • Can we use arrays in classes? Is there anything
    special that we have to do to use them in
    classes?
  • How do we pass or return a single element of an
    array?
  • Make a method declaration that is public, returns
    nothing, is called muglet, and accepts an
    integer array as a parameter.

34
Review- Arrays in Classes.
  • Make a method declaration for a method that is
    public, returns an array of doubles, is called
    blar, and accepts an array of integers.
  • Why do we have to be careful when returning an
    array from a method? What can we do to be safe?

35
Searching/Sorting
36
How to find information in arrays
  • Now that we are able to store information in
    arrays, we also need to be able to find the
    information again and retrieve it.
  • To find information we will perform a searching
    algorithm on the array(well look for the value
    in the array).

37
Sequential search
  • The sequential search is very simple We start at
    the first element in the array, and compare it
    against what we want to find. We continue this
    till the last element in the array. If we ever
    find the value, were done. If we get to the end
    of the array, and we havent found it, then the
    value isnt in the array.

38
Sequential search in code
int toSearchFor 5, i int anArray new
int20 //anArray gets some values from the
user. for(I0 IltanArray.length
I) if(toSearchFor anArrayI)
System.out.println(Found it.)
System.out.println(At location I)
break if(IanArray.length) System.out.prin
tln(Didnt find it.)
39
Other searches
  • There are other searches we can perform that are
    sometimes faster.
  • A binary search can be performed if all of the
    data is in order(like a phone book)
  • Look at the halfway point. If you are at too
    small of a value, disregard the left half and
    proceed searching the right half. If you are at
    too large a value, disregard the right half, and
    look at the left half.

40
Other searches continued...
  • Many of these faster searches, such as a binary
    search, require that our list of information (or
    array) be sorted.
  • We must find some way of sorting an array.

41
Why sorting
  • Organization in general can make things quicker.
    We spend less time looking for things, and more
    time using them. This is why we do sorting. It
    makes our information easier to find and use.
  • The first sorting algorithm we will look at is
    the Selection Sort.

42
Selection Sort algorithm(smallest to largest).
  • For each element i in the list.
  • Find the ith smallest value.
  • Place this value in the ith position.
  • This is probably the most intuitive sort
    algorithm. We need to refine this algorithm more
    before we can use it in Java code, though.

43
Selection Sort algorithm refined.
  • For each ith element in the list
  • For each of the elements from I on
  • compare against the smallest seen so far.
  • Swap the ith value in the list with the ith
    smallest value.

44
Selection sort code
  • See the code on page 426 and 427 for the full
    code of an implementation of the Selection Sort
    algorithm.

45
Swapping-Exchanging values in arrays.
  • Swapping is an important step that occurs in
    every sorting algorithm.
  • The idea is to exchange the value from one index
    with the value located at another index.
  • For this, we will always need a temporary
    variable to store the value from one of the
    elements while it is being overwritten.

46
Other sorting algorithms.
  • There are other sorting algorithms out there, and
    some even run much faster than the selection
    sort.
  • If you would like to do some research, look at
    the Bubble Sort, the Insertion Sort, the Merge
    Sort, and the Quick Sort.

47
Sorting examples in action.
  • View the Sorting demo in the applet demos in the
    directory you installed Java to
    (C\jdk1.3\demo\applets\SortDemo)

48
Searching/Sorting review.
  • Explain the Sequential Search algorithm in your
    own words.
  • Why do we want to do sorting?
  • Explain the Selection Sort algorithm in your own
    words.
  • Are there faster sorting algorithms than the
    Selection Sort algorithm?

49
Sorting Review
  • Go through the steps to do the Selection Sort on
    the following list of numbers
  • 1,5,17,6,3,12,18

50
Multidimensional Arrays
51
Multidimensional arrays
  • We can have arrays with more than a single
    dimension.
  • These are used for things like tables of data,
    game boards, keeping 3/4 dimensional data,
    weather forecasting, etc.
  • Can have as many dimensions as you would like,
    but we usually keep it under 5 dimensions.
  • Most often we will deal with 2-dimensional
    arrays.

52
Declaring multidimensional arrays
  • Just add an extra set of square brackets for
    every dimension.

double excelSheet new double108 dou
ble temps3D new double202020
char ticTacToeBoard new char33
Creates a table with 10 rows, 8 columns.
Creates a 3-Dimensional cube for storing
temperatures in a three dimensional space.
Creates a tic tac toe board with 3 rows, 3 columns
53
2 dimensional tables.
  • Our most common multi-dimensional array.
  • By convention, listed in row-column order.

int numRows 3, numCols 2 int table new
intnumRowsnumCols for(int rows 0 rows
ltnumRows rows) for(int cols 0 cols lt
numCols cols) tablerowscols rowscols
54
What that code created
int numRows 3, numCols 2 int table new
intnumRowsnumCols for(int rows 0 rows
ltnumRows rows) for(int cols 0 cols lt
numCols cols) tablerowscols rowscols
55
Rules about arrays.
  • Make sure you dont reverse the row-column
    ordering. Row-Column. Row-Column. Row-Column. RC,
    RC, RC, Row-Column, Row-Column, Row-Column. RC.
    RC. Row-Column. RC. Row-Column. Row-Column. Row
    Column. Row-Column. Row-Column.
  • You can pass and return multidimensional arrays
    to and from methods like any other array. Just
    make sure you get enough brackets in the method
    declaration.

56
Implementation of arrays.
  • A multi-dimensional array is actually just an
    array of arrays.

int table new int4103 table25.
length //3 table2.length //10 table.length
//4
57
Multidimensional array review.
  • Write a declaration and initialization of a
    3-dimensional array of integers that is sized 3
    by 5 by 7.
  • Are the following declarations legal?
  • int table new int 152352413
  • double anotherTable new double23

58
Multidimensional array review.
Table03 Table54 Table14 Table11
Table00 Table60
14 23 234 3 8 54
Table13 Table34 Table44 Table21
Table30 Table35
4 32 73 23 98 89
59
Review
60
Arrays Review
  • What is an array?
  • What data types can you use in arrays?
  • Declare an array of integers called prices and
    initialize it to have size 10.
  • What are the indices for the prices array?

61
Arrays Review
  • What is output to the screen?
  • int someArray new int20
  • System.out.println(someArray5)
  • What is output to the screen?
  • int someArray new int5
  • someArray5 3
  • System.out.println(someArray5)

62
Arrays Review
  • What is actually stored in an array name?
  • What are the following values?

Prices2 Prices6
Prices3 Prices0
Prices.length
63
Arrays Review
  • Run the selection sort on the following numbers
  • 5,23,1,3,2,15,8

64
Arrays Review
Table11 Table00 Table60
Table21 Table30 Table35
Write a Comment
User Comments (0)
About PowerShow.com