Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 6 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays ** ** multidimensional.

Similar presentations


Presentation on theme: "Chapter 6 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays ** ** multidimensional."— Presentation transcript:

1 Chapter 6 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays ** ** multidimensional arrays will be further discussed in COMP123 Arrays

2 Chapter 6 2 What is an Array? l Array [in general programming] »a contiguous block of equally-sized memory blocks »each block is distinguished by an index, subscript, element number, or location value (all mean the same thing) »all array elements are of the same type (primitive or class) »allow multiple values to be [sort of] referenced by on name l Arrays [in Java] »are older programming structures (list switch/case) »for multi-value storage, you are encouraged to use the advanced Java classes: Lists, Collections, and Vectors l Arrays are treated like objects (reference variables), without the ADT complexity of being instances of classes

3 Chapter 6 3 Creating Arrays l General syntax for declaring an array: type[] array_name = new type[length]; l Examples: int[] heights; // array ref. var. (null array) heights = new int[22]; // array of 22 ints // array of 80 characters char[] symbol = new char[80]; // array of 100 double values double[] reading = new double[100]; // array of 15 Shape objects Shape[] geometries = new Shape[15];

4 Chapter 6 4 Three Position for [ ] (Brackets) when used with Arrays l declaration—to indicate that reference variable is a reference to an array of a specific type »create an int array variable, but not an array! »int[] pressure; l creating (allocating in memory) a new array »pressure = new int[100]; »int[] levels = new int[10]; l indexing a specific element within an array »levels[3] = SavitchIn.readLineInt(); »System.out.print("4th elem."+levels[3]);

5 Chapter 6 5 Array Terminology temperature[n + 2] temperature[n + 2] = 32; array name: temperature index (also called a subscript, location, or element number) - must be an int, - or an expression that evaluates to an int indexed variable (also called element) - holds the value at the index position The term "element" is usually interchangeable with the terms: index, array value, element location, and "array thing at index" data value of the indexed variable - also called an element of the array

6 Chapter 6 6 Array Length l length of an array defined during the: new type[length] statement »determines the number of equally-size data blocks allocated for the array elements »memory locations are allocated, whether or not elements are explicitly given values array length is stored the instance variable length, Species[] entry = new Species[20]; System.out.println( entry.length ); // shows: 20 l array length is established during the new and cannot be changed »although the array reference variable can be "pointed to" a new memory address that identifies another array of smaller, or larger, length! (more on this later)

7 Chapter 6 7 Initializing an Array during Declaration l arrays can be initialised during declaration with a comma- separated list in braces l non- initialised elements are assigned the default value, »0 for numeric arrays, an activated constructor for objects »if only the list is provided, the array is of that length l example: double[] reading = {5.1, 3.02, 9.65}; System.out.println( reading.length ); -displays "3", since array reading has values: [0] = 5.1 [1] = 3.02 [2] = 9.65

8 Chapter 6 8 Subscript Range l array indexes (subscripts) begin at [0] and proceed to [array length-1] »this is similar to character positions in String objects, since String objects use characters arrays to store data int[] scores = {97, 86, 92, 71}; –in place of, int[] scores = new int[4]; scores[0] = 97; scores[1] = 86; scores[2] = 92; scores[3] = 71; l *** if reference is made beyond the [length-1] index, this generates a run-time error: "array subscript out of range" »Java is "array safe"—in C/C++, no error is reported!

9 Chapter 6 9 Initializing Array Elements with a Loop l since arrays are contiguous and of an unchanging size, a for loop is commonly used l array elements of numeric type are initialised to zero (0) during declaration –elements of class type are initialised to null –it is always good to initialise an newly declared array—why? l example: int i; //loop counter/array index int[] a = new int[10]; // 10 elem. int array for(i=0; i<a.length; i++) // loop: 0..9 a[i] = 0; // init. to 0

10 Chapter 6 10 Some things to do with arrays l setting element values to result of method call: for (int i=0; i<ray.length; i++) { System.out.print("Enter value "+i+":"); ray[i] = SavitchIn.readLineInt(); } l summing values in an array: for (int i=0; i<ray.length; i++) sum = sum + ray[i]; l copy one array to another (both of equal length) : for (int i=0; i<array.length; i++) brray[i] = array[i]; l reverse copy of one array to another (both of equal length) : for (int i=0; i<array.length; i++) { upperindex = (array.length-1)-i brray[i] = array[upperindex]; } or for (int i=0, k=array.length-1; i<array.length; i++, k--) brray[i] = array[k];

11 Chapter 6 11 Some things to do with arrays l determine the minimum and maximum values within an array double min=ray[0], // init. both min and max max=ray[0]; // to the first element value for (int i=1; i<ray.length; i++) { if (ray[i] < min) // if current element < min min = ray[i]; // set min to current element if (ray[i] > max) // if current element > max max = ray[i]; // set max to current element } l for the above, could the second if be changed to else if ? l search for the first occurrence of a value & remember location: int loc = 0; // init. loc to first position for(loc=0; ((loc<ray.length) && (ray[loc]!=searchval)); loc++); // after, if loc is < ray.length, item found at loc // if loc is = ray.length, item not found

12 Chapter 6 12 Some things to do with arrays l check to see if two arrays are equal (same order of values): boolean equal=true; // assume they are equal for (int i=0; i<array.length; i++) { if (array[i] != brray[i]) // check if != { equal = false; // set false break; // stop loop } or boolean equal=true; // assume they are equal for (int i=0; equal ; i++) // loop while equal equal = (array[i] == brray[i]); // check equality

13 Chapter 6 13 Arrays and Array Elements as Method Arguments l arrays, and the individual array elements, can be used with classes and methods just like other primitive variable and objects »both an indexed element and the array identifier can be legally used as argument in a method call l through a return statement, methods can return a single array element value, or an array identifier l BUT DO NOT CONFUSE THE ARRAY WITH ITS ELEMENTS!!! »double[] list = new list[100]; »list is not the same as list[2] !!! »list is an array reference, list[2] is a double variable value

14 Chapter 6 14 Array Names as Method Arguments l arrays are similar to objects: the array is a reference variable l arrays arguments given to methods are pass-by-reference »only the memory address is passed to the method »changes to the array in the method, change the original values public static void getArray (int[] array) { for(int i = 0; i < array.length; i++) array[i] = inputInt("Enter value "+(i+1)); }// end of getArray() public static void showArray (int[] array) { for(int i = 0; i < array.length; i++) print( array[i] ); }// end of showArray()

15 Chapter 6 15 Checking Arrays for Equality…in a Method same technique as previous, except now using a method (remember: arrays must be of equal length) public static boolean arrayEquals (double[] a, double[] b) { boolean equal=true; // assume they are equal for (int i=0; i<a.length; i++) if (a[i] != b[i]) // check if != { equal = false; // set false break; // stop loop } return (equal); // return equality status }// end of arrayEquals()

16 Chapter 6 16 Methods that Return an Array l an array is not passed in, but the address of the array is passed back l the local array name c (in main() ) is assigned the address which is returned from the call to vowels() l the local array in vowels(), newarray, is lost when the methods finishes but the address is returned and stored l Java reused memory only when nothing points to it! c, newArray, and the return type of vowels are all the same type: array of char

17 Chapter 6 17 Partially Filled Arrays l sometimes only part of an array contains useful data –consider an array of maximum 100 marks, but there are only 30 students in the class l array elements always contain a value (random or otherwise) l a partially-filled array is a standard array, except that an int is declared to describe the number of used array elements l example: double[] quizzes = double [100]; // 100 quizzes int num_quizzes = 0; // hold # of quizzes

18 Chapter 6 18 Example of a Partially Filled Array quizzes[0]10.5 quizzes[1]20.0 quizzes[2]18.5 quizzes[3] quizzes[4] num_quizzes - 1 unused values num_quizzes will have a value of 3 quizzes.length will have a value of 5

19 Chapter 6 19 Sorting an Array l sorting a list of elements is a common task with arrays –sort values in ascending order (1,2,4,10,12,20,...) –sort values in descending order (20,12,10,4,2,1,...) –sort strings in alphabetic order ("Bob", "Chuck", "Erin",...) l there are many techniques used in sorting »bubble sort, selection sort, shell sort, binary sort, quick sort, … l Selection sort (page 423) »easy to understand and program, although not efficient l Bubble sort (not in text) »also easy to understand and program, very inefficient "the more efficient a sort technique is, the more difficult it is to understand!"

20 Chapter 6 20 Bubble Sort Algorithm l this technique processes an array multiple times and "percolates" (or bubbles) the largest value to the end of the array –"largest to end"—ascending; "smallest to end"—descending –problem with bubble sort: it performs unnecessary sorts l the algorithm (ascending sort): 1. assume the array is filled with out of order element values 2. loop a counter i from the last element index down to 1 (i essentially works down the list, placing the largest at end) 2.1 loop a counter j from 0 up to i (j essentially works up the "unsorted" elements, pushing elements up) 2.1.1 if current element (at [j]) is greater than next (at [j+1]) 2.1.1.1 swap the element values between [j] and [j+1] 3. end of sort, elements are now in sorted order

21 Chapter 6 21 public void bubblesort (int[] ray) { for (int i=ray.length-1; i>=1; i--) // loop last index down to 1 for (int j=0; j<i; j++) // loop 0 up to ith element if (ray[j] > ray[j+1]) // if cur. (j) > next (j+1), then swap (ray, j, j+1) // swap element, put in correct order // nothing to return, since the array is call-by-reference }// end of bubblesort() public void swap (int array[], int pos1, int pos2) { int t; // internal dummary/temporary variable t = array[pos1]; // store value @ pos1 to t array[pos1] = array[pos2]; // store value @ pos2 to pos1 array[pos2] = t; // store t to pos2 }// end of swap() l of course, whether the methods are public static void, or public void, or private void, depends on whether they are –in a program class or utility class –public methods in a proper class, or –private methods used only within a class

22 Chapter 6 22 Multidimensional Arrays l arrays with more than one index »number of dimensions = number of indexes l arrays with more than two dimensions are a simple extension of two-dimensional (2D) arrays l a 2D array corresponds to a table or grid »one dimension is the row »the other dimension is the column »cell: an intersection of a row and column »an array element corresponds to a cell in the table l 2D arrays are actually, 1D arrays in which each element is simply another 1D!

23 Chapter 6 23 Table as a 2-Dimensional Array l The table assumes a starting balance of $1000 l First dimension: row identifier - Year l Second dimension: column identifier - percentage l Cell contains balance for the year (row) and percentage (column) l Balance for year 4, rate 7.00% = $1311 23

24 Table as a 2-D Array l Generalizing to two indexes: [row][column] l First dimension: row index l Second dimension: column index l Cell contains balance for the year/row and percentage/column l All indexes use zero-numbering »Balance[3][4] = cell in 4th row (year = 4) and 5th column (7.50%) »Balance[3][4] = $1311 (shown in yellow) 24 Row Index 3 (4th row) Column Index 4 (5th column)

25 Chapter 6 25 Java Code to Create a 2-D Array l Syntax for 2-D arrays is similar to 1-D arrays Declare a 2-D array of int s named table »the table should have ten rows and six columns int[][] table = new int[10][6];

26 Chapter 6 26 Method to Calculate the Cell Values Each array element corresponds to the balance for a specific number of years and a specific interest rate (assuming a starting balance of $1000): balance(starting, years, rate) = (starting) x (1 + rate) years The repeated multiplication by (1 + rate) can be done in a for loop that repeats years times. balance method in class InterestTable

27 Chapter 6 27 Processing a 2-D Array: for Loops Nested 2-Deep Arrays and for loops are a natural fit To process all elements of an n -D array nest n for loops »each loop has its own counter that corresponds to an index l For example: calculate and enter balances in the interest table »inner loop repeats 6 times (six rates) for every outer loop iteration »the outer loop repeats 10 times (10 different values of years ) »so the inner repeats 10 x 6 = 60 times = # cells in table Excerpt from main() of InterestTable

28 Chapter 6 28 Multidimensional Array Parameters and Returned Values l Methods may have multi-D array parameters l Methods may return a multi-D array as the value returned l The situation is similar to 1-D arrays, but with more brackets Example: a 2-D int array as a method argument Notice how the number of columns is obtained Notice how the number of rows is obtained showTable method from class InterestTable2

29 Chapter 6 29 Ragged Arrays l Ragged arrays have rows of unequal length »each row has a different number of columns, or entries l Ragged arrays are allowed in Java Example: create a 2-D int array named b with 5 elements in the first row, 7 in the second row, and 4 in the third row: int[][] b; b = new int[3][]; b[0] = new int[5]; b[1] = new int[7]; b[2] = new int[4];

30 Chapter 6 30 Summary Part 1 l An array may be thought of as a collection of variables, all of the same type. l An array is also may be thought of as a single object with a large composite value of all the elements of the array. Arrays are objects created with new in a manner similar to objects discussed previously.

31 Chapter 6 31 Summary Part 2 l Array indexes use zero-numbering: »they start at 0, so index i refers to the (i+1)th element; »index of the last element: (length-of-the-array - 1) »Any index value outside the valid range of 0 to length-1 will cause an array index out of bounds error when the program runs. l A method may return an array. l A "partially filled array" is one in which values are stored in an initial segment of the array: »use an int variable to keep track of how many variables are stored.

32 Chapter 6 32 Summary Part 3 l An array indexed variable can be used as an argument to a method anyplace the base type is allowed: »if the base type is a primitive type then the method cannot change the value of the indexed variable; »but if the base type is a class, then the method can change the value of the indexed variable. l When you want to store two or more different values (possibly of different data types) for each index of an array, you can use parallel arrays (multiple arrays of the same length). l An accessor method that returns an array corresponding to a private instance variable of an array type should be careful to return a copy of the array, and not return the private instance variable itself. l The selection sort algorithm can be used to sort an array of numbers into increasing or decreasing order.

33 Chapter 6 33 Summary Part 4 l Arrays can have more than one index. l Each index is called a dimension. l Hence, multidimensional arrays have multiple indexes, »e.g. an array with two indexes is a two-dimensional array. l A two-dimensional array can be thought of as a grid or table with rows and columns: »one index is for the row, the other for the column. l Multidimensional arrays in Java are implemented as arrays of arrays, »e.g. a two-dimensional array is a one-dimensional array of one-dimensional arrays.


Download ppt "Chapter 6 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays ** ** multidimensional."

Similar presentations


Ads by Google