Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Why do we need arrays? Problem - Input 5 test scores => int test1,test2,test3,test4,test5 100 test scores? 10,000 employees? A structured data type is.

Similar presentations


Presentation on theme: "1 Why do we need arrays? Problem - Input 5 test scores => int test1,test2,test3,test4,test5 100 test scores? 10,000 employees? A structured data type is."— Presentation transcript:

1 1 Why do we need arrays? Problem - Input 5 test scores => 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

2 2 Array 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.

3 3 Declaring an array: step 1. dataType[] arrayName; step 2. arrayName = new dataType[size]; 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 > 0. –can be a variable int[] scores; scores = new int[10];

4 Declaring an array: (two steps combined) dataType[] arrayName = new dataType[intExp]; int [] scores = new int[10]; Initializes its components to their default values Numeric arrays are initialized to 0 4

5 Zero-Equivalent Auto-Initialization Values TypeValue int0 double0.0 char‘\0’ booleanfalse objectsnull 5

6 6 int[] scores = new int[10]; scores

7 Specifying Array Size during Program Execution int arraySize; System.out.println(“Enter the size of the array: “); arraySize = console.nextInt(); int[] scores = new int[arraySize]; 7

8 8 Accessing Array Components arrayName[indexExp] indexExp – nonnegative integer reference array elements by using the subscript or the index [] – array subscripting operator Zero based indexing

9 Accessing Array Components new int[n] => subscripts 0 thru n-1 int scores[10] –scores[0] - is the first element of array test –scores[9] - last element of test –scores[10] = 1000; //writes beyond array-Exception scores[4] = 88; 9

10 10 Valid subscripts => can use variables, expression, or constant as subscripts scores[0] = 95; scores[i+2] = scores[i] + scores[i + 1]; x = scores[i]; System.out.println(scores[i * 2] );

11 11 Each array element is treated exactly as a variable buf[5] = 30; scores[1]++; i = buf[8] * 92; System.out.println(buff[80]); if (a[i] < 14) scores[3] = console.nextInt();

12 12 Array 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

13 length 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 13

14 Array traversal Processing each array sequentially from the first to the last for (int i = 0; i.length; i++) ; 14

15 Array limitations You can’t: 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); 15

16 16 Initializing an array to a specific value double[] sales = new double[10]; for (int index = 0; index < sales.length; index++) sales[index] = 10.00;

17 17 Input data into an array double[] sales = new double[10]; for (int index = 0; index < sales.length; index++) { Sysmt.out.println(“Enter value”); sales[index] = console.nextDouble(); }

18 18 Printing an array double[] sales = new double[10]; for (int index = 0; index < sales.length; index++) System.out.println(sales[index]);

19 19 Printing an array System.out.println(Arrays.toString(list)); Yields: [17, -3, 42, 8, 12, 2, 103]

20 20 Finding the sum and average of an array double[] sales = new double[10]; double Sum = 0; for (int index = 0; index < sales.length; index++) sum += sales[index]; double avg = sum/sales.length;

21 21 Determining the largest element of an array double[] sales = new double[10]; int maxIndex = 0; for (int index = 1; index < sales.length; index++) if (sales[maxIndex] < sales[index]) maxIndex = index; double largest = sales[maxIndex];

22 22 Printing an array in reverse order double[] sales = new double[10]; for (int index = sales.length - 1; index >= 0; index--) System.out.println(sales[index];

23 Array 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 9 ArrayIndexOutOfBoundsException for (int i = 0; i <= 10; i++) num[i] = 0; 23

24 Methods: Arrays as Formal Parameters: datatype[] arrayName Size not necessary Because arrays are reference variables, the array can be changed public static void processArrays(int[] listA, double[] listB) 24

25 Arrays as Actual Parameters: pass name of array in call method(arrayName); formal: public static void processArrays (int[] listA, double[] listB); actual: int[] intList = new int[10]; double[] doubleList = new double[15]; processArrays(intList,doubleList); 25

26 26 Method: print an array public static void printArray(int[] list) { for (int index = 0; index < list.length; index++) System.out.println(list[index]); }

27 27 Method: read an array public static void readArray(int[] list) { for (int index = 0; index < list.length; index++) { System.out.println(“Enter value”); list[index] = console.nextInt(); }

28 28 Method: read an array public static int readArray(int[] list, Scanner infile) { index = 0; while (infile.hasNext() && index < list.length) { list[index] = infile.nextInt(); index++; } return index; // number of elements read }

29 29 Method: read an array public static int[] readArray() { for (int index = 0; index < list.length; index++) { System.out.println(“Enter value”); list[index] = console.nextInt(); } return list; }

30 30 Method: sum an array public static int sumArray(int[] list) { int sum = 0; for (int index = 0; index < list.length; index++) sum += list[index]; return sum; }

31 31 Method: return index of largest element public static int indexLargestElement(int[] list) { int maxIndex = 0; for (int index = 1; index < list.length; index++) if (list[index] > list[maxIndex]) maxIndex = index; return maxIndex; }

32 32 Method: copy array public static void copyArray(int[] list1, int[] list2) { for (int index = 0; index < list.length; index++) list2[index] = list1[index]; }

33 Arrays as parameters to methods static final int ARRAY_SIZE = 10; int[] listA = new int[ARRAY_SIZE]; int[] listB = new int[ARRAY_SIZE]; printArray(listA); readArray(listA); copyArray(listA,listB); printArray(listA); printArray(listB); 33

34 Passing an array arrayName  base address arrayName  address of arrayName[0] When you pass an array as a parameter, the base address of the actual array is passed to the formal parameter 34

35 35 Linear Search public static int find(int[] list, int searchItem) { for (int ix = 0; ix < list.length(); ix++) { if (list[i] == searchItem) return ix; } return -1; }

36 36 Linear Search (also called Sequential Search) public static boolean find(int[] list, int searchItem) { int ix = 0; boolean found = false; while (!found && ix < list.length) { if (list[ix] == searchItem) found = true; else ix++ } return found; }

37 37 BINARY 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

38 38 Binary 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 >= first) { middle = (first + last)/2; if (item < list[middle] last = middle - 1; else if (item > list[middle]) first = middle + 1; else found = true; } if (!found) return -1; return middle; }

39 39 Average Number of Iterations

40 For-Each Loop Java 5: Enhanced for loop for ( : ) statement for (int index = 0; index < list.length; index++) System.out.println(list[index]); for (int index: list) System.out.println(index); Usually only applicable for examining each value in sequence 40

41 41 Caution using arrays with = arrayA = arrayB; both will refer to same array Shallow copy use the for loop for a deep copy

42 42 Caution 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”);

43 Comparing two arrays boolean isEqualArrays(int[] firstArray, int[] secondArray) { if (firstArray.length != secondArray.length) return false; for (int index = 0; index < firstArray.length; index++) if (firstArray[index] != secondArray[index]) return false; return true; } if (isEqualArrays(listA, listB) … 43

44 Parallel Arrays Two or more arrays Corresponding components hold related information int[] studentId = new int[50]; char[] courseGrade = new char[50]; int numStudents = 0; while (infile.hasNext() && numStudents < 50) { students[numStudents] = infile.nextInt (); courseGrade[numStudents] = infile.next().charAt(0); numStudents++; } 44

45 Array of String objects String[] nameList = new String[5]; nameList[0] = “Joe Smith”; … Use for loop to output nameList –for (int I = 0; I < nameList.length;i++) System.out.println(namelist[i] ); Also use String methods –nameList[4].substring(0,3) 45

46 Command line arguments public static void main(String[] args) Java DoSomething Java DoSomething temps.txt temps.out args[0] = “temps.txt” args[1] = “temps.out” 46

47 47 Two Dimensional Arrays table with rows and columns all items of the same data type access by row and column indices Example: tables or graphs

48 Declaring a two-dimensional array dataType[][] arrayName arrayName = new dataType[intExp1][intExp2]; dataType[][] arrayName = new dataType[intExp1][intExp2]; 48

49 49 int[][] A= new int[3][4];

50 50

51 51 int A[3][4] Virtually Stored A[0][0] A[0][1] A[0][2] A[0][3] A[1][0] A[1][1] A[1][2] A[1][3] A[2][0] A[2][1] A[2][2] A[2][3]

52 Accessing Array Components arrayName[indexExp1][indexExp2] A[2][3] = 25; Indices can be variables –A[i][j] 52

53 Two-dimensional arrays and the instance variable length Length can be used for number of rows and columns int[] matrix = new int[20][15]; Number of rows = matrix.length is 20 Number of columns - matrix[0].length is 15 53

54 Two dimensional arrays: special cases Can have different number of columns for each row int[][] board; board = new int[5]; //board.length is 5 board[0] = new int[6]; // board[0].length is 6 board[1] = new int[2]; board[2] = new int[5]; board[3] = new int[3]; board[4] = new int[4]; 54

55 Two-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}}; 55

56 Initialize two-dimensional arrays: int[][] matrix = new int[ROWS][COLS]; for (int row = 0; row < matrix.length; row++) for (col = 0; col < matrix[row].length; col++) matrix[row][col] = 10; 56

57 Print two-dimensional arrays int[][] matrix = new int[ROWS][COLS]; for (int row = 0; row < matrix.length; row++) for (col = 0; col < matrix[row].length; col++) System.out.printf(“%7d”,matrix[row][col]) System.out.println(); 57

58 Input two-dimensional arrays int[][] matrix = new int[ROWS][COLS]; for (int row = 0; row < matrix.length; row++) for (col = 0; col < matrix[row].length; col++) matrix[row][col] = console.nextInt(); 58

59 Sum by row: two-dimensional arrays int[][] matrix = new int[ROWS][COLS]; for (int row = 0; row < matrix.length; row++) { sum = 0; for (col = 0; col < matrix[row].length; col++) sum += matrix[row][col]; System.out.println(“The sum of the elements of row “ (row +1) + “ = “ + sum); } 59

60 Sum by column: two- dimensional arrays int[][] matrix = new int[ROWS][COLS]; for (int col = 0; col < matrix[0].length; col++) { sum = 0; for (row = 0; row < matrix.length; row++) sum += matrix[row][col]; System.out.println(“The sum of the elements of column “ (col +1) + “ = “ + sum); } 60

61 61 Passing Two-Dimensional Arrays as Parameters public static void printMatrix(int[][] matrix) { for (int row = 0; row < matrix.length; row++) for (col = 0; col < matrix[row].length; col++) System.out.printf(“%7d”,matrix[row][col]) System.out.println(); } Call: printMatrix(board)

62 62 Multidimensional arrays arrays can have any number of dimensions –dataType[][]..[] arrayName = new dataType[intExp1][intExp2]..[intRxpn]; To access: –arrayName[indexExp1][indexExp2][indexExpn] Requires multiple loops to process

63 63 Multidimensional arrays Example: double [][][] graph = new double[30][30][30]; graph[3][2][5] = 27.68;


Download ppt "1 Why do we need arrays? Problem - Input 5 test scores => int test1,test2,test3,test4,test5 100 test scores? 10,000 employees? A structured data type is."

Similar presentations


Ads by Google