Chapter 9 Arrays Java Programming From Problem Analysis
Chapter 9: Arrays Java Programming: From Problem Analysis to Program Design, Second Edition Java Programming: From Problem Analysis to Program Design,
Chapter Objectives s Learn about arrays. s Explore how to declare and manipulate data into arrays. s Understand the meaning of “array index out of bounds. ” s Become familiar with the restrictions on array processing. Java Programming: From Problem Analysis to Program Design, Second Edition 2
Chapter Objectives s Discover how to pass an array as a parameter to a method. s Discover how to manipulate data in a twodimensional array. s Learn about multidimensional arrays. Java Programming: From Problem Analysis to Program Design, Second Edition 3
Array s Is a collection of a fixed number of components, where all the components are of the same data type. s Components are accessed using their relative positions in the array. Java Programming: From Problem Analysis to Program Design, Second Edition 4
One-Dimensional Arrays s Syntax to instantiate an array: s data. Type[ ] array. Name; array. Name = new data. Type[int. Exp] s data. Type[ ] array. Name 1, array. Name 2; Java Programming: From Problem Analysis to Program Design, Second Edition 5
Array num int[] num = new int[5]; Java Programming: From Problem Analysis to Program Design, Second Edition 6
Alternate Ways to Declare an Array int[] num ; int num[]; int[] list; int list[]; Java Programming: From Problem Analysis to Program Design, Second Edition 7
Alternate ways to declare an array int alpha[] , beta; //line 2 Int[] gamma , delta; //line 3 Java Programming: From Problem Analysis to Program Design, Second Edition 8
One-Dimensional Arrays s Syntax to access an array component: s array. Name[index. Exp] s int. Exp = number of components in array >= 0 s 0 <= index. Exp < int. Exp Java Programming: From Problem Analysis to Program Design, Second Edition 9
Accessing Array Components int[] list = new int [10]; list[5] = 34; or i = 5; list[i] = 34; or i = 4; list[2 * i – 3] = 34; Java Programming: From Problem Analysis to Program Design, Second Edition 10
Array list Java Programming: From Problem Analysis to Program Design, Second Edition 11
Array Declaration s final int ARRAY_SIZE = 10; s int[] list = new int[ARRAY_SIZE]; Java Programming: From Problem Analysis to Program Design, Second Edition 12
Specifying Array Size During Program Execution int array. Size; System. out. print("Enter the size of " + "the array: "); array. Size = console. next. Int(); System. out. println(); int[] list = new int[array. Size]; Dynamic arrays Java Programming: From Problem Analysis to Program Design, Second Edition 13
Array Initialization During Declaration double[] sales = {12. 25, 32. 50, 16. 90, 23, 45. 68}; s The values, called initial values, are placed between braces and separated by commas. s Here, sales[0]= 12. 25, sales[1]= 32. 50, sales[2]= 16. 90, sales[3]= 23. 00, and sales[4]= 45. 68. s When declaring and initializing arrays, the size of the array is determined by the number of initial values within the braces. s If an array is declared and initialized simultaneously, we do not use the operator new to instantiate the array object. Java Programming: From Problem Analysis to Program Design, Second Edition 14
Arrays and the Instance Variable length s A public instance variable length is associated with each array that has been instantiated. s The variable length contains the size of the array. s The variable length can be directly accessed in a program using the array name and the dot operator. s Consider the following declaration: int[] list = {10, 20, 30, 40, 50, 60}; s This statement creates the array list of six components and initializes the components using the values given. Here list. length is 6. Java Programming: From Problem Analysis to Program Design, Second Edition 15
Arrays and the Instance Variable length s This statement creates the array num. List of 10 components and initializes each component to 0. int[] num. List = new int[10]; s The value of num. List. length is 10. s These statements store 5, 10, 15, and 20, respectively, in the first four components of num. List[0] = 5; num. List[1] = 10; num. List[2] = 15; num. List[3] = 20; s You can store the number of filled elements, that is, the actual number of elements, in the array in a variable, say no. Of. Element. It is a common practice for a program to keep track of the number of filled elements in an array. Java Programming: From Problem Analysis to Program Design, Second Edition 16
Processing One-Dimensional Arrays s Loops used to step through elements in array and perform operations. int[] list = new int[100]; int i; for (i = 0; i < list. length; i++) //process list[i], the (i + 1)th //element of list for (i = 0; i < list. length; i++) list[i] = console. next. Int(); for (i = 0; i < list. length; i++) System. out. print(list[i] + " "); Java Programming: From Problem Analysis to Program Design, Second Edition 17
Arrays s Some operations on arrays: s s Initialize Input data Output stored data Find largest/smallest/sum/average of elements double[] sales = new double[10]; int index; double largest. Sale, sum, average; Java Programming: From Problem Analysis to Program Design, Second Edition 18
Code to Initialize Array to Specific Value (10. 00) for (index = 0; index < sales. length; index++) sales[index] = 10. 00; Java Programming: From Problem Analysis to Program Design, Second Edition 19
Code to Read Data into Array for (index = 0; index < sales. length; index++) sales[index] = console. next. Double(); Java Programming: From Problem Analysis to Program Design, Second Edition 20
Code to Print Array for (index = 0; index < sales. length; index++) System. out. print(sales[index] + " "); Java Programming: From Problem Analysis to Program Design, Second Edition 21
Code to Find Sum and Average of Array sum = 0; for (index = 0; index < sales. length; index++) sum = sum + sales[index]; if (sales. length != 0) average = sum / sales. length; else average = 0. 0; Java Programming: From Problem Analysis to Program Design, Second Edition 22
Determining Largest Element in Array max. Index = 0; for (index = 1; index < sales. length; index++) if (sales[max. Index] < sales[index]) max. Index = index; largest. Sale = sales[max. Index]; Java Programming: From Problem Analysis to Program Design, Second Edition 23
Determining Largest Element in Array Java Programming: From Problem Analysis to Program Design, Second Edition 24
s Example 9 -4 Java Programming: From Problem Analysis to Program Design, Second Edition 25
Array Index Out of Bounds s An array is in bounds if: 0 <= index <= array. Size – 1 s If index < 0 or index > array. Size: In Java, if an array index goes out of bounds during program execution, it throws an Array. Index. Out. Of. Bounds. Exception exception. If the program does not handle this exception, the program terminates with an appropriate error message. Java Programming: From Problem Analysis to Program Design, Second Edition 26
Declaring Arrays as Formal Parameters to Methods General syntax to declare an array as a formal parameter: data. Type[] array. Name public static void arrays. As. Formal. Parameter(int[] list. A, double[] list. B, int num) { //. . . } int[] int. List = new int[10]; double[] double. Num. List = new double[15]; int number; arrays. As. Formal. Parameter(int. List, double. Num. List, number); Java Programming: From Problem Analysis to Program Design, Second Edition 27
The Assignment Operators and Arrays int[] list. A = {5, 10, 15, 20, 25, 30, 35}; int[] list. B= new int[list. A. length]; Java Programming: From Problem Analysis to Program Design, Second Edition 28
The Assignment Operators and Arrays Java Programming: From Problem Analysis to Program Design, Second Edition 29
The Assignment Operators and Arrays list. B = list. A; Java Programming: From Problem Analysis to Program Design, Second Edition 30
The Assignment Operators and Arrays Java Programming: From Problem Analysis to Program Design, Second Edition 31
The Assignment Operators and Arrays Shallow copying of data Java Programming: From Problem Analysis to Program Design, Second Edition 32
The Assignment Operators and Arrays for (int index = 0; index < list. A. length; index++) list. B[index] = list. A[index]; Java Programming: From Problem Analysis to Program Design, Second Edition 33
The Assignment Operators and Arrays deep copying of data Java Programming: From Problem Analysis to Program Design, Second Edition 34
Relational Operators Arrays if (list. A == list. B). . . s The expression list. A == list. B determines if the values of list. A and list. B are the same, thus determining whether list. A and list. B refer to the same array. s To determine whether list. A and list. B contain the same elements, you need to compare them component by component. s You can write a method that returns true if two int arrays contain the same elements. Java Programming: From Problem Analysis to Program Design, Second Edition 35
Relational Operators and Arrays boolean is. Equal. Arrays(int[] first. Array, int[] second. Array) { if (first. Array. length != second. Array. length) return false; for (int index = 0; index < first. Array. length; index++) if (first. Array[index] != second. Array[index]) return false; return true; } if (is. Equal. Arrays(list. A, list. B)). . . Java Programming: From Problem Analysis to Program Design, Second Edition 36
Methods for Array Processing To write methods to process arrays, in addition to declaring an array as a formal parameter, we declare another formal parameter specifying the number of elements in the array. Java Programming: From Problem Analysis to Program Design, Second Edition 37
Methods for Array Processing public static void fill. Array(int[] list, int no. Of. Elements) { int index; for (index = 0; index < no. Of. Elements; index++) list[index] = console. next. Int(); } Java Programming: From Problem Analysis to Program Design, Second Edition 38
Methods for Array Processing public static void fill. Array(int[] list, int no. Of. Elements) { int index; for (index = 0; index < no. Of. Elements; index++) list[index] = console. next. Int(); } Java Programming: From Problem Analysis to Program Design, Second Edition 39
Methods for Array Processing public static void print. Array(int[] list, int no. Of. Elements) { int index; for (index = 0; index < no. Of. Elements; index++) System. out. print(list[index] + " "); } public static int sum. Array(int[] list, int no. Of. Elements) { int index; int sum = 0; for (index = 0; index < no. Of. Elements; index++) sum = sum + list[index]; return sum; } Java Programming: From Problem Analysis to Program Design, Second Edition 40
Methods for Array Processing public static int index. Largest. Element(int[] list, int no. Of. Elements) { int index; int max. Index = 0; for (index = 1; index < no. Of. Elements; index++) if (list[max. Index] < list[index]) max. Index = index; return max. Index; } public static void copy. Array(int[] list 1, int[] list 2, int no. Of. Elements) { int index; for (index = 0; index < no. Of. Elements; index++) list 2[index] = list 1[index]; } Java Programming: From Problem Analysis to Program Design, Second Edition 41
Base Address of an Array s The base address of an array is the address (memory location) of the first array component. s The base address of list is the address of list[0] Java Programming: From Problem Analysis to Program Design, Second Edition 42
Parallel Arrays s Arrays are parallel if the corresponding components hold related information. Java Programming: From Problem Analysis to Program Design, Second Edition 43
Parallel Arrays int[] student. Id = new int[50]; char[] course. Grade = new char[50]; Int no. Of. Students = 0; While (infile. has. Next() && no. Of. Student < 50) { student. Id[no. Of. Students] = infile. next. Int(); course. Grade[no. Of. Students] = infile. next(). char. At(0); no. Of. Students++; } Java Programming: From Problem Analysis to Program Design, Second Edition 44
Arrays of Objects s Can use arrays to manipulate objects. s Example: Create an array named array 1 with N objects of type T: T[] array 1 = new T[N] s Can instantiate array 1 as follows: for(int j=0; j <array 1. length; j++) array 1[j] = new T(); Java Programming: From Problem Analysis to Program Design, Second Edition 45
Array of String Objects String[] name. List = new String[5]; name. List[0] name. List[1] name. List[2] name. List[3] name. List[4] = = = "Amanda Green"; "Vijay Arora"; "Sheila Mann"; "Rohit Sharma"; "Mandy Johnson"; Java Programming: From Problem Analysis to Program Design, Second Edition 46
Array of String Objects Java Programming: From Problem Analysis to Program Design, Second Edition 47
Array of String Objects To output the names!! Java Programming: From Problem Analysis to Program Design, Second Edition 48
Array of String Objects You can use String methods to work with the objects of name. List. For example, the expression: name. List[0]. equals("Amanda Green") evaluates to true. Java Programming: From Problem Analysis to Program Design, Second Edition 49
Arrays of Objects Clock[] arrival. Time. Emp = new Clock[100]; Java Programming: From Problem Analysis to Program Design, Second Edition 50
Instantiating Array Objects for (int j = 0; j < arrival. Time. Emp. length; j++) arrival. Time. Emp[j] = new Clock(); Java Programming: From Problem Analysis to Program Design, Second Edition 51
Instantiating Array Objects Java Programming: From Problem Analysis to Program Design, Second Edition 52
Instantiating Array Objects arrival. Time. Emp[49]. set. Time(8, 5, 10); Java Programming: From Problem Analysis to Program Design, Second Edition 53
Arrays and Variable Length Parameter List s The syntax to declare a variable length formal parameter (list) is: data. Type. . . identifier Java Programming: From Problem Analysis to Program Design, Second Edition 54
Arrays and Variable Length Parameter List public static double largest(double. . . num. List) { double max; int index; if (num. List. length != 0) { max = num. List[0]; for (index = 1; index < num. List. length; index++) { if (max < num. List[index]) max = num. List[index]; } return max; } return 0. 0; } Java Programming: From Problem Analysis to Program Design, Second Edition 55
Arrays and Variable Length Parameter List double num 1 = largest(34, 56); double num 2 = largest(12. 56, 84, 92); double num 3 = largest(98. 32, 77, 64. 67, 56); System. out. println(largest(22. 50, 67. 78, 92. 58, 45, 34, 56)); double[] number. List = {18. 50, 44, 56. 23, 17. 89 92. 34, 112. 0, 77, 11, 22, 86. 62); System. out. println(largest(number. List)); Java Programming: From Problem Analysis to Program Design, Second Edition 56
Arrays and Variable Length Parameter List Example 9 -7 Java Programming: From Problem Analysis to Program Design, Second Edition 57
The following are some rules to follow when using a variable length formal parameter list: 1. A method can have both a variable length formal parameter and other formal parameters. For example, consider the following method heading: public static void my. Method(String name, double num, int. . . int. List) 2. A method can have at most one variable length formal parameter. 3. If a method has both a variable length formal parameter and other types of formal parameters, then the variable length formal parameter must be the last formal parameter of the formal parameter list. Java Programming: From Problem Analysis to Program Design, Second Edition 58
foreach loop s The syntax to use this for loop to process the elements of an array is: for (data. Type identifier : array. Name) statements s identifier is a variable, and the data type of identifier is the same as the data type of the array components. Java Programming: From Problem Analysis to Program Design, Second Edition 59
foreach loop sum = 0; for (double num : list) sum = sum + num; s The for statement is read for each num in list. The identifier num is initialized to list[0]. In the next iteration, the value of num is list[1], and so on. • The for loop of the method largest: for (double num : num. List) { if (max < num) max = num; } Java Programming: From Problem Analysis to Program Design, Second Edition 60
Example 9 -8 Example 9 -9 Java Programming: From Problem Analysis to Program Design, Second Edition 61
Two-Dimensional Arrays s Data is sometimes in table form (difficult to represent using a one-dimensional array). s To declare/instantiate a two-dimensional array: data. Type[ ][ ] array. Name = new data. Type[int. Exp 1][int. Exp 2]; s To access a component of a two-dimensional array: array. Name[index. Exp 1][index. Exp 2]; s int. Exp 1, int. Exp 2 >= 0 s index. Exp 1 = row position s index. Exp 2 = column position Java Programming: From Problem Analysis to Program Design, Second Edition 62
Two-Dimensional Arrays double[][]sales = new double[10][5]; Java Programming: From Problem Analysis to Program Design, Second Edition 63
Accessing Two-Dimensional Array Components sales[5][3] = 25. 75; Java Programming: From Problem Analysis to Program Design, Second Edition 64
Accessing Two-Dimensional Array Components i = 5; j = 3; sales[i][j] = 25. 75; Java Programming: From Problem Analysis to Program Design, Second Edition 65
Two-Dimensional Arrays and the Instance Variable length s Given a two-dimensional array A, the number of rows can be determined from: A. length s The number of columns in a row can be determined from: A[row. Index]. length Example: int[][] matrix = new int[20][15]; matrix. length; //is 20 matrix[0]. length; //is 15 Java Programming: From Problem Analysis to Program Design, Second Edition 66
Processing Two-Dimensional Arrays s Three ways to process two-dimensional arrays: s Entire array. s Particular row of array (row processing). s Particular column of array (column processing). s Processing algorithms is similar to processing algorithms of one-dimensional arrays. Java Programming: From Problem Analysis to Program Design, Second Edition 67
1. row processing. for (col = 0; col < matrix[5]. length; col++) //process matrix[5][col] or row= 5; for (col = 0; col < matrix[row]. length; col++) //process matrix[row][col] 2. column processing. for (row = 0; row < matrix. length; row++) //process matrix[row][2] or col= 2; for (row = 0; row < matrix. length; row++) //process matrix[row][col] Java Programming: From Problem Analysis to Program Design, Second Edition 68
Two-Dimensional Arrays: Processing Initialization for (row = 0; row < matrix. length; row++) for (col = 0; col < matrix[row]. length; col++) matrix[row][col] = 10; Print for (row = 0; row < matrix. length; row++) { for (col = 0; col < matrix[row]. length; col++) System. out. printf("%7 d", matrix[row][col]); System. out. println(); } Java Programming: From Problem Analysis to Program Design, Second Edition 69
Two-Dimensional Arrays: Processing Input for (row = 0; row < matrix. length; row++) for (col = 0; col < matrix[row]. length; col++) matrix[row][col] = console. next. Int(); Sum by Row (sum of each individual row): for (row = 0; row < matrix. length; row++) { sum = 0; for (col = 0; col < matrix[row]. length; col++) sum = sum + matrix[row][col]; System. out. println("Sum of row " + (row + 1) + " = "+ sum); } Java Programming: From Problem Analysis to Program Design, Second Edition 70
Two-Dimensional Arrays: Processing Sum by Column (sum of each individual column): for (col = 0; col < matrix[0]. length; col++) { sum = 0; for (row = 0; row < matrix. length; row++) sum = sum + matrix[row][col]; System. out. println("Sum of column " + (col + 1) + " = " + sum); } Java Programming: From Problem Analysis to Program Design, Second Edition 71
Two-Dimensional Arrays: Processing Largest Element in Each Row for (row = 0; row < matrix. length; row++) { largest = matrix[row][0]; for (col = 1; col < matrix[row]. length; col++) if (largest < matrix[row][col]) largest = matrix[row][col]; System. out. println("The largest element of row " + (row + 1) + " = " + largest); } Java Programming: From Problem Analysis to Program Design, Second Edition 72
Two-Dimensional Arrays: Processing Largest Element in Each Column for (col = 0; col < matrix[0]. length; col++) { largest = matrix[0][col]; for (row = 1; row < matrix. length; row++) if (largest < matrix[row][col]) largest = matrix[row][col]; System. out. println("The largest element of col " + (col + 1) + " = " + largest); } Java Programming: From Problem Analysis to Program Design, Second Edition 73
Reversing Diagonals Self study If you have any questions ask after reading Java Programming: From Problem Analysis to Program Design, Second Edition 74
Passing Two-Dimensional Arrays as Parameters to Methods Just like one-dimensional arrays, twodimensional arrays can be passed as parameters to a method. Java Programming: From Problem Analysis to Program Design, Second Edition 75
Note When storing a two-dimensional array in the computer’s memory, Java uses the row order form; the first row is stored first, followed by the second row, followed by the third row, and so on. Java Programming: From Problem Analysis to Program Design, Second Edition 76
Multidimensional Arrays s Can define three-dimensional arrays or n-dimensional arrays (n can be any number). s Syntax to declare and instantiate array: data. Type[][]…[] array. Name = new data. Type[int. Exp 1][int. Exp 2]…[int. Expn]; s Syntax to access component: array. Name[index. Exp 1][index. Exp 2]…[index. Expn] s int. Exp 1, int. Exp 2, . . . , int. Expn = positive integers s index. Exp 1, index. Exp 2, . . . , index. Expn = non-negative integers Java Programming: From Problem Analysis to Program Design, Second Edition 77
A three dimensional array Arr[0][5][1] 0 1 2 3 4 5 0 1 2 Java Programming: From Problem Analysis to Program Design, Second Edition 78
Loops to Process Multidimensional Arrays double[][][] car. Dealers = new double[10][5][7]; For (i = 0; i < 10; i++) for (j = 0; j < 5; j++) for (k = 0; k < 7; k++) car. Dealers[i][j][k] = 10. 00; Java Programming: From Problem Analysis to Program Design, Second Edition 79
Programming Example: Text Processing s Program: Reads given text; outputs the text as is; prints number of lines and number of times each letter appears in text. s Input: File containing text to be processed. s Output: File containing text, number of lines, number of times each letter appears in text. Java Programming: From Problem Analysis to Program Design, Second Edition 80
Programming Example Solution: Text Processing s An array of 26 representing the letters in the alphabet. s Three methods: s copy. Text s character. Count s write. Total s Value in appropriate index is incremented using methods and depends on character read from text. Java Programming: From Problem Analysis to Program Design, Second Edition 81
Chapter Summary s Arrays s Definition s Uses s Different arrays s s One-dimensional Two-dimensional Multidimensional (n-dimensional) Arrays of objects Parallel arrays Java Programming: From Problem Analysis to Program Design, Second Edition 82
Chapter Summary s Declaring arrays s Instantiating arrays s Processing arrays s Entire array s Row processing s Column processing s Common operations and methods performed on arrays s Manipulating data in arrays Java Programming: From Problem Analysis to Program Design, Second Edition 83
- Slides: 83