Title: Why do we need arrays?
1Why do we need arrays?
- Problem - Input 5 test scores gt
- int test1,test2,test3,test4,test5
- 100 test scores? 10,000 employees?
- A structured data type is a type that
- Stores a collection of individual components
- The whole collection has just one variable name
- Allows individual components from the collection
to be stored and retrieved
2Array
- structured collection of components (called array
elements) - all elements are of the same data type
- Array has one single name
- Array elements stored in adjacent memory
locations. - access individual components by using the array
name together with index in square brackets - The index indicates the position of the component
within the collection.
3Declaring an arraystep 1. dataType
arrayNamestep 2. arrayName new dataTypesize
- dataType -type of data stored in each component
of the array - int, float, char, etc
- arrayName - the name of the array
- An array is an object, arrayName is a reference
variable - size - number of components/members in the array
- Integer expression,must have a value gt 0.
- can be a variable
- int scores
- scores new int10
4Declaring an array (two steps combined)dataType
arrayName new dataTypeintExp
- int scores new int10
- Initializes its components to their default
values - Numeric arrays are initialized to 0
5Zero-Equivalent Auto-Initialization Values
Type Value
int 0
double 0.0
char \0
boolean false
objects null
6int scores new int10
7Specifying Array Size during Program Execution
- int arraySize
- System.out.println(Enter the size of the array
) - arraySize console.nextInt()
- int scores new intarraySize
8Accessing Array ComponentsarrayNameindexExp
- indexExp nonnegative integer
- reference array elements by using the subscript
or the index - array subscripting operator
- Zero based indexing
9Accessing Array Components
- new intn gt subscripts 0 thru n-1
- int scores10
- scores0 - is the first element of array test
- scores9 - last element of test
- scores10 1000 //writes beyond
array-Exception - scores4 88
10Valid subscriptsgt can use variables,
expression, or constant as subscripts
- scores0 95
- scoresi2 scoresi scoresi 1
- x scoresi
- System.out.println(scoresi 2 )
11Each array element is treated exactly as a
variable
- buf5 30
- scores1
- i buf8 92
- System.out.println(buff80)
- if (ai lt 14)
- scores3 console.nextInt()
12Array Initialization during Declaration
- by declaration
- int age 23, 34, 18, 44, 50
- double temps 0.0, 112.37, 98.6
- compiler will allocate space for each initialized
item - new is not required here
13length
- You can use the built-in length property to
determine the size of any array. - System.out.println(anArray.length)
- will print the array's size
- length contains the size of the array
- int list 10,20,30,40,50,60
- list.length is 6
14Array traversal
- Processing each array sequentially from the first
to the last - for (int i 0 i lt ltarraygt.length i)
- ltdo something with arrayigt
15Array limitations
- You cant
- change the size of an array in the middle of
program execution (ArrayList class) - compare arrays for equality using
- print an array with
- System.out.println(arrayName)
16Initializing an array to a specific value
- double sales new double10
- for (int index 0 index lt sales.length
index) - salesindex 10.00
17Input data into an array
- double sales new double10
- for (int index 0 index lt sales.length
index) -
- Sysmt.out.println(Enter value)
- salesindex console.nextDouble()
-
-
18Printing an array
- double sales new double10
- for (int index 0 index lt sales.length
index) - System.out.println(salesindex)
19Printing an array
- System.out.println(Arrays.toString(list))
- Yields
- 17, -3, 42, 8, 12, 2, 103
20Finding the sum and average of an array
- double sales new double10
- double Sum 0
- for (int index 0 index lt sales.length
index) - sum salesindex
- double avg sum/sales.length
21Determining the largest element of an array
- double sales new double10
- int maxIndex 0
- for (int index 1 index lt sales.length
index) - if (salesmaxIndex lt salesindex)
- maxIndex index
- double largest salesmaxIndex
22Printing an array in reverse order
- double sales new double10
- for (int index sales.length - 1 index gt 0
index--) - System.out.println(salesindex
23Array Index out of Bounds Exception
- double num new double 10
- int i//i can be 0,1, 2, 3, 4, 5, 6, 7, 8, 9
- index out of bounds i lt 0 or i gt 9
- ArrayIndexOutOfBoundsException
- for (int i 0 i lt 10 i)
- numi 0
24MethodsArrays as Formal Parametersdatatype
arrayName
- Size not necessary
- Because arrays are reference variables, the array
can be changed - public static void processArrays(int listA,
-
double listB)
25Arrays as Actual Parameterspass name of array
in callmethod(arrayName)
- formal
- public static void processArrays (int listA,
-
double listB) - actual
- int intList new int10
- double doubleList new double15
- processArrays(intList,doubleList)
26Method print an array
- public static void printArray(int list)
-
- for (int index 0 index lt list.length
index) - System.out.println(listindex)
27Method read an array
- public static void readArray(int list)
-
- for (int index 0 index lt list.length
index) -
- System.out.println(Enter value)
- listindex console.nextInt()
-
28Method read an array
- public static int readArray(int list,
-
Scanner infile) -
- index 0
- while (infile.hasNext() index lt
list.length) -
- listindex infile.nextInt()
- index
-
- return index // number of elements read
29Method read an array
- public static int readArray()
-
- for (int index 0 index lt list.length
index) -
- System.out.println(Enter value)
- listindex console.nextInt()
-
- return list
30Method sum an array
- public static int sumArray(int list)
-
- int sum 0
- for (int index 0 index lt list.length
index) - sum listindex
- return sum
31Method return index of largest element
- public static int indexLargestElement(int list)
-
- int maxIndex 0
- for (int index 1 index lt list.length
index) - if (listindex gt listmaxIndex)
- maxIndex index
- return maxIndex
32Method copy array
- public static void copyArray(int list1, int
list2) -
- for (int index 0 index lt list.length
index) - list2index list1index
33Arrays as parameters to methods
- static final int ARRAY_SIZE 10
- int listA new intARRAY_SIZE
- int listB new intARRAY_SIZE
- printArray(listA)
- readArray(listA)
- copyArray(listA,listB)
- printArray(listA)
- printArray(listB)
34Passing an array
- arrayName ? base address
- arrayName ? address of arrayName0
- When you pass an array as a parameter, the base
address of the actual array is passed to the
formal parameter
35Linear Search
- public static int find(int list, int
searchItem) -
- for (int ix 0 ix lt list.length() ix)
-
- if (listi searchItem)
- return ix
-
- return -1
-
36Linear Search(also called Sequential Search)
- public static boolean find(int list, int
searchItem) -
- int ix 0
- boolean found false
- while (!found ix lt list.length)
-
- if (listix searchItem)
- found true
- else
- ix
-
- return found
-
37BINARY SEARCH
- requires sorted list
- (Ex phone books, dictionaries).
- keep dividing list in half, compare against
middle argument - eliminates one half of the elements after each
comparison. - efficient
38Binary Search
- public static int binSearch(int list, int
searchItem) -
- int first 0 // lower bound on
list - int last length - 1 // upper bound on
list - int middle // middle index
- boolean found false
- while (!found last gt first)
-
- middle (first last)/2
- if (item lt listmiddle
- last middle - 1
- else if (item gt listmiddle)
- first middle 1
- else
- found true
-
- if (!found)
- return -1
- return middle
39Average Number of Iterations
40For-Each Loop
- Java 5 Enhanced for loop
- for (lttypegt ltindexNamegt ltarrayNamegt)
- statement
- for (int index 0 index lt list.length index)
- System.out.println(listindex)
- for (int index list)
- System.out.println(index)
- Usually only applicable for examining each value
in sequence
41Caution using arrays with
- arrayA arrayB
- both will refer to same array
- Shallow copy
- use the for loop for a deep copy
42Caution using arrays with
- if(arrayA arrayB)
- Returns true if they refer to the same array
- arrays.equals provided
-
- if (arrays.equals(list1, list2))
- System.out.println(The arrays are equal)
43Comparing two arrays
- boolean isEqualArrays(int firstArray, int
secondArray) -
- if (firstArray.length ! secondArray.length)
- return false
- for (int index 0 index lt firstArray.length
index) - if (firstArrayindex ! secondArrayindex)
- return false
- return true
-
- if (isEqualArrays(listA, listB)
44Parallel Arrays
- Two or more arrays
- Corresponding components hold related information
- int studentId new int50
- char courseGrade new char50
- int numStudents 0
- while (infile.hasNext() numStudents lt 50)
-
- studentsnumStudents infile.nextInt ()
- courseGradenumStudents infile.next().charAt(
0) - numStudents
-
45Array of String objects
- String nameList new String5
- nameList0 Joe Smith
- Use for loop to output nameList
- for (int I 0 I lt nameList.lengthi)
- System.out.println(namelisti )
- Also use String methods
- nameList4.substring(0,3)
46Command line arguments
- public static void main(String args)
- Java DoSomething
- Java DoSomething temps.txt temps.out
- args0 temps.txt
- args1 temps.out
47Two Dimensional Arrays
- table with rows and columns
- all items of the same data type
- access by row and column indices
- Example tables or graphs
48Declaring a two-dimensional array
- dataType arrayName
- arrayName new dataTypeintExp1intExp2
- dataType arrayName new dataTypeintExp1int
Exp2
49int A new int34
50(No Transcript)
51A00
A01
A02
A03
A10
A11
A12
A13
A20
A21
A22
A23
52Accessing Array Components
- arrayNameindexExp1indexExp2
- A23 25
- Indices can be variables
- Aij
53Two-dimensional arrays and the instance variable
length
- Length can be used for number of rows and columns
- int matrix new int2015
- Number of rows matrix.length is 20
- Number of columns - matrix0.length is 15
54Two dimensional arrays special cases
- Can have different number of columns for each row
- int board
- board new int5 //board.length is 5
- board0 new int6 // board0.length is 6
- board1 new int2
- board2 new int5
- board3 new int3
- board4 new int4
55Two-dimensional array initialization during
declaration
- Elements of each row are enclosed within braces
and separated by commas - All rows are enclosed in braces
- int board1 2, 3, 1,
- 15, 25, 13,
- 20, 4, 7,
- 11, 18, 14
- int board2 2, 3, 1, 5,
- 15, 25,
- 11, 18, 10
56Initialize two-dimensional arrays
- int matrix new intROWSCOLS
- for (int row 0 row lt matrix.length row)
- for (col 0 col lt matrixrow.length
col) - matrixrowcol 10
57Print two-dimensional arrays
- int matrix new intROWSCOLS
- for (int row 0 row lt matrix.length row)
- for (col 0 col lt matrixrow.length
col) - System.out.printf(7d,matrixrowcol)
- System.out.println()
58Input two-dimensional arrays
- int matrix new intROWSCOLS
- for (int row 0 row lt matrix.length row)
- for (col 0 col lt matrixrow.length
col) - matrixrowcol console.nextInt()
-
59Sum by row two-dimensional arrays
- int matrix new intROWSCOLS
- for (int row 0 row lt matrix.length row)
-
- sum 0
- for (col 0 col lt matrixrow.length
col) - sum matrixrowcol
- System.out.println(The sum of the elements of
row - (row 1)
sum) -
-
60Sum by column two-dimensional arrays
- int matrix new intROWSCOLS
- for (int col 0 col lt matrix0.length col)
-
- sum 0
- for (row 0 row lt matrix.length row)
- sum matrixrowcol
- System.out.println(The sum of the elements of
column - (col 1)
sum) -
-
61Passing Two-Dimensional Arrays as Parameters
- public static void printMatrix(int matrix)
-
- for (int row 0 row lt matrix.length row)
- for (col 0 col lt matrixrow.length
col) - System.out.printf(7d,matrixrowcol)
- System.out.println()
-
- Call printMatrix(board)
62Multidimensional arrays
- arrays can have any number of dimensions
- dataType.. arrayName new
dataTypeintExp1intExp2..intRxpn - To access
- arrayNameindexExp1indexExp2indexExpn
- Requires multiple loops to process
63Multidimensional arrays
- Example
- double graph new double303030
- graph325 27.68