Lecture 05 - Arrays
Introduction useful and powerful aggregate data structure Arrays allow us to store arbitrary sized sequences of primitive values or sequences of references to objects easily access and manipulate the values/objects that they store Arrays are indexed by a sequence of integers classes use arrays as instance variables to store databases of value/references
Declaring Arrays int[] A = new int[5];
More About Arrays an array is a homogeneous data structure: each of its members stores the same type (either primitive or reference) the indexes go from 0 to one less than the length of the array each array object stores a public final int length instance variable that stores the length of the array we can access the value stored in this field, in the example above, by writing a.length int[] a = new int[]{4, 2, 0, 1, 3}; another way to create an array
Arrays
Accessing Arrays int[] a = new int[]{4, 2, 0, 1, 3}; System.out.println( a[0] ); if (a[2] == 0)...some statement if the value computed for the index is less than 0, or greater than OR EQUAL TO the length of the array – trying to access the memember at that index cause Java to throw the ArrayIndexOutOfBoundsException which contains a message showing what index was attempted to be accessed An array of Strings – String[] s = new String[]{"ABC", "LMN", "XYZ"};
A Graphical View
Processing Arrays Typically, a for loop is used to generate all the indexes for the array object. Study the following code carefully; int sum = 0; for (int i=0; i < a.length; i++) – sum += a[i]; System.out.println("Sum = " + sum);
More Code What is the output of the following code? for (int i=0; i < a.length; i++) System.out.print(a[i]+" "); System.out.println(); The following code computes and prints the maximum value stored in an array int max = a[0]; for (int i=1; I<a.length; i++) if (a[I] > max) max = a[i]; System.out.println("Max = " + max);
Arrays - Review An array is a data structure that groups and organizes data l Array is a list of values (int, double, aggregates) l The number corresponding to each position is called an index or subscript Index = 0 Value = 12 Index = 2 Value = 16 Index = 1 Value = 10
Declaring and using Arrays Arrays are objects Int [] height = new int[11] New operator allocates memory space to save values The type of the array is int [] Eg: Random x = new Random(); final int LIMIT = 15; int [] list = new int[LIMIT] for (int I=0; I<LIMIT;I++) { list[I] = x.nextInt(LIMIT);} for (int I=0; I<LIMIT;I++) { System.out.print(list[I]+”\t”);}
Declaring and using Arrays Two ways to declare arrays: int [] grades; int grades[]; No difference as far as compiler is concerned First one is more consistent with type declarations int [] A, B, C; int A[], B, C[];
Interactively Read a set of numbers into an Array import javax.swing.JOptionPane; boolean done = false; final int LIMIT = 15; int [] list = new int[LIMIT]; int index = 0; Int num; While (true) { num =Integer.parseInt( JOptionPane.showInputDialog("Enter an integer")); if (I==LIMIT-1 || num==-999) break; else list[I++] = num; }
An Array Example final int NUMCHARS = 26; String line = JOptionPane.showInputDialog("Enter a sentence"); char current; int other= 0; int [] upper = new int[NUMCHARS]; For (int I=0; I<line.length(); I++) { current = line.charAt(I); if (current >= ‘A’ && current <= ‘Z’) upper[current-’A’]++; } What does above program do?
More on Arrays Array Intializer int [] list = {1,2,3,4}; Array as Parameter An entire array can be passed as a parameter to a method A copy of the reference to the array is passed A method can change array elements permanently A method cannot change the reference itself
Two Dimensional Arrays (Matrices) A Table (Grid) of Rows and Columns Uses Two Indexes to refer to an element Two Dimensional Array(or Matrix) is an array of Arrays Eg: int [][] Table = new int[5][10]; for (int I=0; I<Rows; I++) for (int j=0;j<Cols;j++) Table[I][j]=I+j; for (int I=0;I<Table.length; I++) for (int j=0;j<Table[I].length;j++) System.out.print(Table[I][j]);
Two Dimensional Arrays ctd.. Int [][] Scores = {{2,3,3},{2,2,2}}; Defines a 2 by 3 matrix (I.e 2 rows and 3 columns) Finding Row Sum of Row 0 (first row) for (int j=0; j<Scores[0].length;j++) sum += Scores[0][j]; Finding Column Sum of Column 2 (third column) for (int i=0; i<Scores.length;i++) sum += Scores[i][2];
Exercises Write a method to find the row sum of a matrix Write a method to find the column sum of a matrix Write a method to find the maximum element in a matrix Write a method to swap two rows of a matrix