Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Arrays.

Similar presentations


Presentation on theme: "Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Arrays."— Presentation transcript:

1 Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Arrays

2 Copyright © 2014 by John Wiley & Sons. All rights reserved.2 Arrays  An array collects a sequence of values of the same type  Sequence of values are called elements  The sequence of values are store under a single name.  An array can be visualized as a series of boxes, each capable of holding a single value belonging to this type:  An array whose elements are arranged in a linear fashion is said to be a one-dimensional array.

3 Copyright © 2014 by John Wiley & Sons. All rights reserved.3 Declaring arrays  An array declaration contains [ and ] symbols (“square brackets”): int[] a;  The elements of an array can be of any type. In particular, array elements can be objects: String[] b;  It’s also legal to put the square brackets after the array name: int a[]; String b[];

4 Copyright © 2014 by John Wiley & Sons. All rights reserved.4 Declaring Arrays  Declaring an array variable doesn’t cause Java to allocate any memory for the array’s elements.  One way to allocate this memory is to use the new keyword: a = new int[10];  You can declare and reserve memory for array at the same time: int[] a = new int[10];  The value inside the square brackets can be any expression that evaluates to a single int value: int n = 10; int[] a = new int[n];

5 Copyright © 2014 by John Wiley & Sons. All rights reserved.5 Initializing arrays  When an array is created using new, the elements of the array are given default values: Numbers are set to zero. boolean elements are set to false. Array and object elements are set to null.  E.g int[] values = new int[10]; 0000000000 0123456789 values

6 Copyright © 2014 by John Wiley & Sons. All rights reserved.6 Arrays  Array elements are indexed by position number Start index: 0 End index: array length – 1  Each index position uniquely identifies an element. a 0000000000 0123456789 Index values First index is always 0 Last index is always length-1

7 Copyright © 2014 by John Wiley & Sons. All rights reserved.7 Initializing array element values  Method 1: Initialize array at the time it’s declared specify the initial values when you create the array double[] values ={32, 54, 67.5, 29, 35, 80, 115, 44.5, 100, 65 }; Do NOT use keyword new You don’t need to specify number of elements.  Method 2: use the [] operator double[] values = new double[10]; Specify index of element: values[4] = 35; values[1] = 20; 325467.529358011544.510065 0123456789 020003500000 0123456789

8 Copyright © 2014 by John Wiley & Sons. All rights reserved.8 Accessing Array Elements  Individual elements are accessed by an integer index i, using the notation array[i] where array is the array name values[3]  An array element can be used like any variable: System.out.println(values[4]); Result = 10.0 + values[2];

9 Copyright © 2014 by John Wiley & Sons. All rights reserved.9 Arrays Figure 1 An Array of Size 10

10 Copyright © 2014 by John Wiley & Sons. All rights reserved.10 Syntax 7.1 Arrays

11 Copyright © 2014 by John Wiley & Sons. All rights reserved.11 Programming Question  Write a tester program called ArrayDemo. Class should declare an int array called values of 5 elements. Assign each element the value of its index. Print all elements along with the index.  A sample run is shown: values[0] = 0 values[1] = 1 values[2] = 2 values[3] = 3 values[4] = 4 Print the values variable. What happens? Modify the program so that you have 1000 elements. As previous, each element should store value of it’s index. Try printing value at index=1000. What happens?

12 Copyright © 2014 by John Wiley & Sons. All rights reserved.12 Answer public class ArrayDemo{ public static void main(String args[]) { final int n = 10; int values[] = new int[n]; for(int i=0; i<n;i++) { values[i] = i; } for(int i=0; i<n;i++) { System.out.printf("values[%d]=%d\n", i, values[i]); } System.out.println("values = "+values); System.out.println("values[10]="+values[10]); } ArrayDemo.java

13 Copyright © 2014 by John Wiley & Sons. All rights reserved.13

14 Copyright © 2014 by John Wiley & Sons. All rights reserved.14 Arrays – Bounds Error  A error you just saw is called a bounds error  Bounds error occurs if you supply an invalid array index.  Causes your program to terminate with a run-time error.  Example: double[] values = new double[10]; values[10] = value; // Error, non-existing index

15 Copyright © 2014 by John Wiley & Sons. All rights reserved.15 Array Length  values.length yields the length of the values array.  There are no parentheses following length.  When iterating through elements in an already initialized array, we use this: for(int i=0; i<values.length;i++) { values[i] = i; }

16 Copyright © 2014 by John Wiley & Sons. All rights reserved.16 Declaring Arrays

17 Copyright © 2014 by John Wiley & Sons. All rights reserved.17 Array References  Copying an array reference yields a second reference to the same array. (like objects)  When you copy an array variable into another, both variables refer to the same array int[] scores = { 10, 9, 7, 4, 5 }; int[] values = scores; // Copying array reference  You can modify the array through either of the variables: scores[3] = 10; System.out.println(values[3]); // Prints 10

18 Copyright © 2014 by John Wiley & Sons. All rights reserved.18 Array References Figure 2 Two Array Variables Referencing the Same Array int[] scores = { 10, 9, 7, 4, 5 }; int[] values = scores; // Copying array reference

19 Copyright © 2014 by John Wiley & Sons. All rights reserved.19 Using Arrays with Methods  Arrays can occur as method arguments and return values.  An array as a method argument public void addScores(int[] values) { for (int i = 0; i < values.length; i++) { totalScore = totalScore + values[i]; } } To call this method int[] scores = { 10, 9, 7, 10 }; fred.addScores(scores);  A method with an array return value public int[] getScores()

20 Copyright © 2014 by John Wiley & Sons. All rights reserved.20 Partially Filled Arrays  Array length = maximum number of elements in array.  Usually, array is partially filled  Define an array larger than you will need final int LENGTH = 100; double[] values = new double[LENGTH];  How do you find out how many elements are actually in the array?

21 Copyright © 2014 by John Wiley & Sons. All rights reserved.21 Partially Filled Arrays  How do you find out how many elements are actually in the array? Use companion variable to keep track of current size: call it currentSize

22 Copyright © 2014 by John Wiley & Sons. All rights reserved.22 Partially Filled Arrays  A loop to fill the array int currentSize = 0; Scanner in = new Scanner(System.in); while (in.hasNextDouble()) { if (currentSize < values.length) { values[currentSize] = in.nextDouble(); currentSize++; } }  At the end of the loop, currentSize contains the actual number of elements in the array.  Note: Stop accepting inputs when currentSize reaches the array length.

23 Copyright © 2014 by John Wiley & Sons. All rights reserved.23 Partially Filled Arrays

24 Copyright © 2014 by John Wiley & Sons. All rights reserved.24 Partially Filled Arrays  To process the gathered array elements, use the companion variable, not the array length: for (int i = 0; i < currentSize; i++) { System.out.println(values[i]); }  With a partially filled array, you need to remember how many elements are filled.

25 Copyright © 2014 by John Wiley & Sons. All rights reserved.25 Question Given an array of integers containing the first five prime numbers, int[] primes = { 2, 3, 5, 7, 11 }; what does it contain after executing the following loop? for (int i = 0; i < 2; i++) { primes[4 - i] = primes[i]; }

26 Copyright © 2014 by John Wiley & Sons. All rights reserved.26 Answer Answer: 2, 3, 5, 3, 2 Given an array of integers containing the first five prime numbers, int[] primes = { 2, 3, 5, 7, 11 }; what does it contain after executing the following loop? for (int i = 0; i < 2; i++) { primes[4 - i] = primes[i]; }

27 Copyright © 2014 by John Wiley & Sons. All rights reserved.27 Programming Question  Write a class ArrayDemo2 to do the following: Define a double array called rainfall of 100 elements. Initialize each element by user keyboard input. User can any time denote that he/she is done entering numbers by inputting non-number value. i.e. user is not required to enter values for all 100 elements.  Calculate and print average rainfall.  A sample run is shown: >Enter rainfall: 20 30 45 65.8 34 A > The average rainfall is 38.96

28 Copyright © 2014 by John Wiley & Sons. All rights reserved.28 Answer import java.util.Scanner; public class ArrayDemo2 { public static void main(String args[]) { double[] rainfall = new double[100]; Scanner in = new Scanner(System.in); System.out.println("Enter rainfall: "); int currentSize=0; do { if(currentSize < rainfall.length) { rainfall[currentSize] = in.nextDouble(); currentSize++; } }while(in.hasNextDouble()); double average = 0.0; double total = 0.0; for(int i=0;i<currentSize;i++) { total += rainfall[i]; } average = total/currentSize; System.out.printf("Average rainfall=%3.2f", average); } ArrayDemo2.java

29 Copyright © 2014 by John Wiley & Sons. All rights reserved.29 The Enhanced for Loop  You can use the enhanced for loop to visit all elements of an array.  E.g. Totaling the elements in an array with the enhanced for loop double[] values = {10.5, 3.2, 6.7}; double total = 0; for (double element : values) //for each element in array { total = total + element; }  The loop body is executed for each element in the array values.  Indices are not accessible Element typeElement nameArray name

30 Copyright © 2014 by John Wiley & Sons. All rights reserved.30 The Enhanced for Loop  Traditional alternative: for (int i = 0; i < values.length; i++) { double element = values[i]; total = total + element; } Indices are accessible

31 Copyright © 2014 by John Wiley & Sons. All rights reserved.31 The Enhanced for Loop  Not suitable for all array algorithms. Does not allow you to modify the contents of an array.  E.g. The following loop does not fill an array with zeros: for (double element : values) { element = 0; // ERROR: this assignment does not modify // array elements }  Use a basic for loop instead: for (int i = 0; i < values.length; i++) { values[i] = 0; // OK }

32 Copyright © 2014 by John Wiley & Sons. All rights reserved.32 The Enhanced for Loop  Use the enhanced for loop if you do not need the index values in the loop body.  The enhanced for loop is a convenient mechanism for traversing all elements in a collection.

33 Copyright © 2014 by John Wiley & Sons. All rights reserved.33 Syntax 7.2 The Enhanced for Loop

34 Copyright © 2014 by John Wiley & Sons. All rights reserved.34 Programming Question  Given the following array: int[] a = {2, 78, 6,67, 23, 2, 7, 8, 0, 23}  Write ArrayDemo3 class to write a method to find and print the maximum of array elements: public static int maximum(int values[]) Modify main method to call this method with array a as parameter

35 Copyright © 2014 by John Wiley & Sons. All rights reserved.35 Answer import java.util.Scanner; public class ArrayDemo3{ public static void main(String args[]) { int[] a = {2, 78, 6,67, 23, 2, 7, 8, 0, 23}; System.out.println(“maximum= "+ maximum(a)); } public static int maximum(int values[]) { int largest = values[0]; for (int i = 1; i < values.length; i++) { if (values[i] > largest) { largest= values[i]; } return largest; } ArrayDemo3.java

36 Copyright © 2014 by John Wiley & Sons. All rights reserved.36 Question Consider the algorithm to find the largest element in an array. Why don’t we initialize largest and i with zero, like this? double largest = 0; for (int i = 0; i < values.length; i++) { if (values[i] > largest) { largest = values[i]; } double largest = values[0]; for (int i = 1; i < currentSize; i++){ if (values[i] > largest){ largest = values[i]; } Original code:

37 Copyright © 2014 by John Wiley & Sons. All rights reserved.37 Answer If all elements of values are negative, then the result is incorrectly computed as 0.

38 Copyright © 2014 by John Wiley & Sons. All rights reserved.38 Programming Question  Linear Search:  Given the following array: int[] a = {2, 78, 6,67, 23, 2, 7, 8, 0, 23}  Write ArrayDemo4 class to add a method to search for a value and print index of element in array if found. Otherwise print “not found!” public static void search(int searhedValue, int values[]) Modify main method to call this method with search value 23 and array a as parameter public static void main(String args[]) { int[] a = {2, 78, 6,67, 23, 2, 7, 8, 0, 23}; search(78, a); search(28, a); }

39 Copyright © 2014 by John Wiley & Sons. All rights reserved.39 Answer import java.util.Scanner; public class ArrayDemo4{ public static void main(String args[]) { int[] a = {2, 78, 6,67, 23, 2, 7, 8, 0, 23}; search(78, a); search(28, a); } public static void search (int searchedValue, int values[]) { int index = 0; boolean found = false; while (index < values.length && !found) { if (values[index] == searchedValue) { found = true; } else { index++; } } if (found) { System.out.println("Found at position: " + index); } else { System.out.println("Not found"); } }

40 Copyright © 2014 by John Wiley & Sons. All rights reserved.40 Common Array Algorithm: Linear Search  This algorithm is called a linear search.  A linear search inspects elements in sequence until a match is found.  To search for a specific element, visit the elements and stop when you encounter the match.

41 Copyright © 2014 by John Wiley & Sons. All rights reserved.41 Common Array Algorithm: Removing an Element Problem: -array: values - current number of elements : currentSize -remove the element at index: pos  How to do this in a: Unordered array? (order of elements does not matter) Ordered array? (order of elements must be maintained)

42 Copyright © 2014 by John Wiley & Sons. All rights reserved.42 Common Array Algorithm: Removing an Element Figure 6 Removing an Element in an Unordered Array  Unordered 1.Overwrite the element to be removed with the last element of the array. values[pos] = values[currentSize - 1]; 2.Decrement the currentSize variable. currentSize--;

43 Copyright © 2014 by John Wiley & Sons. All rights reserved.43 Common Array Algorithm: Removing an Element  Ordered array 1.Move all elements following the element to be removed to a lower index. for (int i = pos + 1; i < currentSize; i++){ values[i - 1] = values[i]; } 2.Decrement the variable holding the size of the array. currentSize--; Figure 7 Removing an Element in an Ordered Array

44 Copyright © 2014 by John Wiley & Sons. All rights reserved.44 Common Array Algorithm: Inserting an Element Figure 8 Inserting an Element in an Unordered Array  If order does not matter 1.Insert the new element at the end of the array. 2.Increment the variable tracking the size of the array. if (currentSize < values.length){ currentSize++; values[currentSize -1 ] = newElement; }

45 Copyright © 2014 by John Wiley & Sons. All rights reserved.45 Common Array Algorithm: Inserting an Element  If order matters : Increment the variable tracking the size of the array. 1.Move all elements after the insertion location to a higher index. 2.Insert the element. if (currentSize < values.length){ currentSize++; for (int i = currentSize - 1; i > pos; i--) { values[i] = values[i - 1]; } values[pos] = newElement; } Figure 9 Inserting an Element in an Ordered Array

46 Copyright © 2014 by John Wiley & Sons. All rights reserved.46 Question When inserting an element into an array, we moved the elements with larger index values, starting at the end of the array. Why is it wrong to start at the insertion location, like this? for (int i = pos; i < currentSize - 1; i++) { values[i + 1] = values[i]; } for (int i = pos + 1; i < currentSize; i++) { values[i - 1] = values[i]; } Original code:

47 Copyright © 2014 by John Wiley & Sons. All rights reserved.47 Answer This loop sets all elements to values[pos].

48 Copyright © 2014 by John Wiley & Sons. All rights reserved.48 Programming Question  Write a program ArrayDemo5 that reverse array in-place. Hint swap elements at same distance to array middle  Use following template to get started: public class ArrayDemo5{ public static void main(String args[]) { int[] a = {2, 78, 6,67, 23}; printArray("before reverse:", a); reverse(a); printArray("after reverse:", a); } public static void reverse(int vals[]) { //TODO } public static void printArray(String message, int ar[]) { System.out.println(message); for(int i=0; i<ar.length;i++) { System.out.println("ar["+i+"]="+ar[i]); }

49 Copyright © 2014 by John Wiley & Sons. All rights reserved.49  Sample output: > java ArrayDemo5 before reverse: ar[0]=2 ar[1]=78 ar[2]=6 ar[3]=67 ar[4]=23 after reverse: ar[0]=23 ar[1]=67 ar[2]=6 ar[3]=78 ar[4]=2 >

50 Copyright © 2014 by John Wiley & Sons. All rights reserved.50 Answer public class ArrayDemo5 { public static void main(String args[]) { int[] a = {2, 78, 6,67, 23}; printArray("before swap:", a); swap(a); printArray("after swap:", a); } public static void swap (int vals[]) { for(int i=0;i<vals.length/2;i++) { int temp = vals[i]; vals[i] = vals[vals.length-i-1]; vals[vals.length-i-1] = temp; } } public static void printArray(String message, int ar[]) { System.out.println(message); for(int i=0; i<ar.length;i++) { System.out.println("ar["+i+"]="+ar[i]); } ArrayDemo5.java Should go only half the length. Array elements at indices i and (length-1)-I are swapped

51 Copyright © 2014 by John Wiley & Sons. All rights reserved.51 Common Array Algorithm: Swapping Elements  To swap two elements, you need a temporary variable.  We need to save the first value in the temporary variable before replacing it. double temp = values[i]; values[i] = values[j];  Now we can set values[j] to the saved value. values[j] = temp;

52 Copyright © 2014 by John Wiley & Sons. All rights reserved.52 Common Array Algorithm: Swapping Elements Figure 10 Swapping Array Elements

53 Copyright © 2014 by John Wiley & Sons. All rights reserved.53 Common Array Algorithm: Copying an Array  Copying an array variable yields a second reference to the same array: double[] values = {1, 3, 45, 5, 20} double[] prices = values;  To make a true copy of an array, call the Arrays.copyOf method: double[] prices = Arrays.copyOf(values, values.length); Explore javadoc API page for Arrays

54 Copyright © 2014 by John Wiley & Sons. All rights reserved.54

55 Copyright © 2014 by John Wiley & Sons. All rights reserved.55

56 Copyright © 2014 by John Wiley & Sons. All rights reserved.56

57 Copyright © 2014 by John Wiley & Sons. All rights reserved.57 Common Array Algorithm: Copying an Array Figure 11 Copying an Array Reference versus Copying an Array

58 Copyright © 2014 by John Wiley & Sons. All rights reserved.58 Common Array Algorithm: Growing an Array  To grow an array that has run out of space, use the Arrays.copyOf method to double the length of an array double[] newValues = Arrays.copyOf(values, 2 * values.length); values = newValues;

59 Copyright © 2014 by John Wiley & Sons. All rights reserved.59 Common Array Algorithm: Growing an Array Figure 12 Growing an Array

60 Copyright © 2014 by John Wiley & Sons. All rights reserved.60 Reading Input  To read a sequence of arbitrary length: Add the inputs to an array until the end of the input has been reached. Grow when needed. double[] inputs = new double[INITIAL_SIZE]; int currentSize = 0; while (in.hasNextDouble()) { // Grow the array if it has been completely filled if (currentSize >= inputs.length) { inputs = Arrays.copyOf(inputs, 2 * inputs.length); // Grow the inputs array } inputs[currentSize] = in.nextDouble(); currentSize++; } Discard unfilled elements. inputs = Arrays.copyOf(inputs, currentSize);

61 Copyright © 2014 by John Wiley & Sons. All rights reserved.61 Two-Dimensional Arrays  An arrangement consisting of rows and columns of values Also called a matrix.  Example: medal counts of the figure skating competitions at the 2010 Winter Olympics. Figure 13 Figure Skating Medal counts

62 Copyright © 2014 by John Wiley & Sons. All rights reserved.62 Two-Dimensional Arrays  Use a two-dimensional (2-D)array to store tabular data.  When constructing a two-dimensional array, specify how many rows and columns are needed: final int COUNTRIES = 7; //number of rows (dimension 1) final int MEDALS = 3; //number of columns (dimension 2) int[][] counts = new int[COUNTRIES][MEDALS];  2-d array of 7 rows and 3 columns OR  7 arrays each having 3 elements (array of arrays) rows columns

63 Copyright © 2014 by John Wiley & Sons. All rights reserved.63 Two-Dimensional Arrays  int[][] counts = new int[COUNTRIES][MEDALS]; counts memory Each row is a 1-d array

64 Copyright © 2014 by John Wiley & Sons. All rights reserved.64 Two-Dimensional Arrays  Method1:  You can declare and initialize the array by grouping each row: int[][] counts = { { 1, 0, 1 }, { 1, 1, 0 }, { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 1 }, { 1, 1, 0 } };  You cannot change the size of a two-dimensional array once it has been declared.

65 Copyright © 2014 by John Wiley & Sons. All rights reserved.65 Two-Dimensional Arrays  Method2:  Assign values to individual elements:  E.g. counts[0][2]=1 [0] [1] [2] [0] [1] [2] [3] [4] [5] [6] row=0, column-2

66 Copyright © 2014 by John Wiley & Sons. All rights reserved.66 Syntax 7.3 Two-Dimensional Array Declaration

67 Copyright © 2014 by John Wiley & Sons. All rights reserved.67 Accessing Elements  Access by using two index values, array[i][j] int medalCount = counts[3][1];

68 Copyright © 2014 by John Wiley & Sons. All rights reserved.68 Question  Given int[][] rating= new int[3][4];  What is the value of rating.length ?  What is the value of rating[0].length ?  What is the value of rating[0] ? Use DrJava interaction pane to find out!

69 Copyright © 2014 by John Wiley & Sons. All rights reserved.69 Answer  Given int[][] rating= new int[3][4];  What is the value of rating.length ? Answer: 3, the number of rows (first dimension)  What is the value of rating[0].length ? Answer: 4, the number of columns (second dimension)  What is the value of rating[0] ? Answer: {0,0,0,0} Use nested loops to access all elements in a two-dimensional array.

70 Copyright © 2014 by John Wiley & Sons. All rights reserved.70 Programming Question  Write ArrayDemo6 class to declare and initialize the counts array and then print the values in the array in a tabular format. Hint: for printing the row and column headers, define two separate arrays Number of rows: counts.length Number of columns: counts[0].length  A sample program run is shown below: Program template in next slide

71 Copyright © 2014 by John Wiley & Sons. All rights reserved.71  Start by copying the following code to ArrayDemo6.java main method: int[][] counts = { { 1, 0, 1 }, { 1, 1, 0 }, { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 1 }, { 1, 1, 0 } }; //headers String[] columnHeader = {"Country", "Gold", "Silver", "Bronze"}; String[] rowHeader = {"Canada", "China", "Germany", "Korea", "Japan", "Russia", "United States"}; //TODO:print column headers //TODO:print array in tabular format Hint: use System.out.printf statements

72 Copyright © 2014 by John Wiley & Sons. All rights reserved.72 Answer public class ArrayDemo6{ public static void main(String args[]){ int[][] counts = {{ 1, 0, 1 }, { 1, 1, 0 }, { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 1 }, { 0, 1, 1 }, { 1, 1, 0 } }; //iniialize headers String[] columnHeader = {"Country", "Gold", "Silver", "Bronze"}; String[] rowHeader = {"Canada","China","Germany","Korea","Japan","Russia","United States"}; //print column headers for(int i = 0; i < columnHeader.length; i++)//for each column { System.out.printf("%15s",columnHeader[i]); //print column header } System.out.println(); //print array in tabular format for (int i = 0; i < counts.length; i++) //for each row { //print row header System.out.printf("%15s",rowHeader[i]); for (int j = 0; j < counts[0].length; j++)//for each element in row i { System.out.printf("%15d", counts[i][j]); //print element } System.out.println(); } ArrayDemo6.java

73 Copyright © 2014 by John Wiley & Sons. All rights reserved.73 Programming Question  Modify ArraysDemo6.java to print a new column with the total number of medals won by each country Hint: This is same as sum of each row  A sample run is shown below:

74 Copyright © 2014 by John Wiley & Sons. All rights reserved.74 Accessing Rows and Columns  Hint To find the number of medals won by a country – Find the sum of the elements in a row  To find the sum of the i th row compute the sum of counts[i][j], where j ranges from 0 to MEDALS - 1.

75 Copyright © 2014 by John Wiley & Sons. All rights reserved.75 Answer public class ArrayDemo6{ public static void main(String args[]){ int[][] counts = {{ 1, 0, 1 }, { 1, 1, 0 }, { 0, 0, 1 }, { 1, 0, 0 },{ 0, 1, 1 }, { 0, 1, 1 }, { 1, 1, 0 } }; //iniialize headers String[] columnHeader = {"Country", "Gold", "Silver", "Bronze","Total"}; String[] rowHeader = {"Canada","China","Germany","Korea","Japan","Russia","United States"}; //print column headers for(int i = 0; i < columnHeader.length; i++)//for each column { System.out.printf("%15s",columnHeader[i]); //print column header } System.out.println(); //print array in tabular format for (int i = 0; i < counts.length; i++) //for each row { //print row header System.out.printf("%15s",rowHeader[i]); int total = 0; for (int j = 0; j < counts[0].length; j++)//for each element in row i { System.out.printf("%15d", counts[i][j]); //print element total += counts[i][j]; } System.out.printf("%15d", total); //print total System.out.println(); } ArrayDemo6.java

76 Copyright © 2014 by John Wiley & Sons. All rights reserved.76 Accessing Rows and Columns  To find the sum of the j th column Form the sum of counts[i][j], where i ranges from 0 to COUNTRIES – 1 int total = 0; for (int i = 0; i < COUNTRIES; i++ { total = total + counts[i][j]; }

77 Copyright © 2014 by John Wiley & Sons. All rights reserved.77 Ragged Arrays  Does every row in a 2d array need to be the same size?  No!  An array with different length rows is said to be ragged.

78 Copyright © 2014 by John Wiley & Sons. All rights reserved.78 Initializing Ragged Arrays  E.g.: int[][] x= { { 710, 1000}, { 790, 1830, 1090}, {2190, 3020, 2050, 1540} };

79 Copyright © 2014 by John Wiley & Sons. All rights reserved.79 Processing Ragged Arrays  Ragged arrays can be useful, but have a big pitfall It is very easy to get ArrayIndexOutOfBounds error for(row = 0; row < matrix.length; row++) { for(col = 0; col < matrix[0].length; col++) { System.out.printf("%7d", matrix[row][col]); } System.out.println(); } How do we correct this?

80 Copyright © 2014 by John Wiley & Sons. All rights reserved.80 Programming Question  Write a class ArrayDemo7 with a method countOcc that counts the number of times each digit between 0 and 9 occurs in a 2d array: void countOcc(int[][] a, int[] count)  Use following main to test the countOcc method: public static void main(String args[]){ int[] counts = new int[10]; int[][] myArray = {{23, 0,9},{2,56,7,-2},{5,5,7},{8,45}}; countOcc(myArray, counts); for(int i=0;i<counts.length;i++) System.out.println("counts["+i+"]="+counts[i]); } Hint: use a 1-d array counts to keep track of counts of each number 0-9  For example, in above array, the output should be: counts[0]=1 counts[1]=0 counts[2]=1 counts[3]=0 counts[4]=0 counts[5]=2 counts[6]=0 counts[7]=2 counts[8]=1 counts[9]=1

81 Copyright © 2014 by John Wiley & Sons. All rights reserved.81 Answer public class ArrayDemo7 { public static void main(String args[]) { int[] counts = new int[10]; int[][] myArray = {{23, 0,9},{2,56,7,-2},{5,5,7},{8,45}}; countOcc(myArray, counts); for(int i=0;i<counts.length;i++) System.out.println("counts["+i+"]="+counts[i]); } public static void countOcc(int[][] a, int[] count) { for(int i=0;i<a.length;i++) { for(int j=0;j<a[i].length;j++) { if(a[i][j]>9 || a[i][j]<0) continue; count[a[i][j]]++; } ArrayDemo7.java


Download ppt "Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Arrays."

Similar presentations


Ads by Google