Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Modelling 1-D Array Overview l Why do we need 1-D array l 1-D array declaration and Initialization l Accessing elements of a 1-D array l Passing Array.

Similar presentations


Presentation on theme: "1 Modelling 1-D Array Overview l Why do we need 1-D array l 1-D array declaration and Initialization l Accessing elements of a 1-D array l Passing Array."— Presentation transcript:

1 1 Modelling 1-D Array Overview l Why do we need 1-D array l 1-D array declaration and Initialization l Accessing elements of a 1-D array l Passing Array as parameter l Array Cloning l Preview: Modelling Multi-Dimensional Arrays

2 2 Why do we need data 1-D array? l There are many applications where several data values are needed in the memory at same time. l Example, counting number of students who perform below average in a class of 30. l Obviously we need to scan through the list of values two times; » first to compute the average and »second to count those below average. l To solve this problem, do we need to declare 30 variables or do we read the values the second time? l Both of these solutions are not convenient l This is even more so when data size is expected to grow very larger. l One convenient solution to this and similar problems is array. l An array is a contiguous list of memory cells that can be identified using a single variable.

3 3 Array Declaration l An array is declared as shown below int [] grades = new int[10]; l Another way to declare array, which is not as readable as above is: int grades[] = new int[10]; l Each of the above methods declares an int array of size 10 which cab be shown as a diagram as below, but we discourage the use of the second method: l Other examples of array declaration are shown below. Notice that the last example where two arrays are declared at the same time is discouraged. float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750]; int[] first = new int[100], second = new int [200]; grades Index0123456789

4 4 Bounds Checking Once an array is created, it has a fixed size Each array object has a public constant called length that stores the size of the array The length of an array object is referenced through the array name  just like any other object: grades.length An index used in an array reference must specify a valid element -- must be in the range 0 to N-1 for an array of N elements. The Java interpreter will throw an exception if an array index is out of bounds. This is called automatic bounds checking.

5 5 Initializer List An initializer list can be used to instantiate and initialize an array in one step The values are delimited by braces and separated by commas as shown below int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] letterGrades = {'A', 'B', ‘C’ 'D', 'F'}; Notice that in the above examples, it is actually the compiler that fills the gap. Thus, in the first example, the compiler would do the following: int[] units = new int[10]; units[0]=147; units[1]=323;...; units[9]=476; Observe that when an initializer list is used: the new operator is not used no size value is specified

6 6 Accessing elements of an Array A particular cell in an array can be referenced using the array name followed by the index of the cell in brackets. For example, the following statement stores 20 in the cell whose index is 4 (cell number 5) grades[4] = 20; The following example demonstrates array index processing. Each cell is initialized to zero. class FillOneDArray { public static void main (String args[]) { int[] grades = new int[10]; for (int i=0; i < grades.length; i++) grades[i] = 0; } Notice that the only modification needed for the above function to handle a different array size, say 20, is in line 3. The loop remains the same. grades 20 Index0123456789

7 7 Passing Array as a parameter l An entire array can be passed to a method as a parameter l Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other l Changing an array element in the method changes the original l Example class ParameterPassingExample { public static void main(String [] args){ int i; int [] a = {1, 2, 3, 4}; double d = 5.5; System.out.println("After initialization"); for (i = 0; i < 4; i++) System.out.println("a["+i+"]="+a[i]); System.out.println("d = " + d); System.out.println("Calling tryToChange."); tryToChange(a, d); System.out.println("Back from tryToChange"); for (i = 0; i < 4; i++) System.out.println("a["+i+"]="+a[i]); System.out.println("d = " + d); }

8 8 Passing Array as a parameter (cont’d) private static void tryToChange(int [] arr, double dd) { int i; dd = 3.14; arr[0] = 55; arr[3] = 100; for (i = 0; i < 4; i++) System.out.println("arr["+i+"]="+arr[i]); System.out.println("dd = " + dd); } Sample output After initialization a[0]= 1 a[1]= 2 a[2]= 3 a[3]= 4 d = 5.5 Calling tryToChange... arr[0]= 55 arr[1]= 2 arr[2]= 3 arr[3]= 100 dd = 3.14 Back from tryToChange a[0]= 55 a[1]= 2 a[2]= 3 a[3]= 100 d = 5.5

9 9 More examples: Printing students who score below average in a quiz l Suppose we have ID number and scores of students in a quiz stored in a text file, QuizScores.txt. l The first column represents the ID numbers, the second represent the scores and the values -1, -1 indicates end of file. l Then the following program prints the scores and statistics such as min, max, mean and list of students who performed below average. import TextIO; class StatisticsExample { private static final int MAX_STUDENTS = 50; private static final double INFINITY= 99999999.9; private static final String DATA_FILE= "QuizScores.txt"; public static void main (String[] args) throws java.io.IOException { long[] ids = new long[MAX_STUDENTS]; double[] scores = new double[MAX_STUDENTS]; double min=INFINITY, max= -INFINITY, sum=0.0; double mean; long minID = -1, maxID = -1; int numOfStudents = 0;

10 10 More examples: Printing students below average in a quiz (cont’d) // declare a channel to data source TextIO in = new TextIO(DATA_FILE); //other variables int i; do { ids[numOfStudents] = in.readLong(); scores[numOfStudents] = in.readDouble(); numOfStudents++; } while (ids[numOfStudents-1] > 0); numOfStudents--; for (i = 0; i < numOfStudents; i++) { sum += scores[i]; if (scores[i] > max) { max = scores[i]; maxID = ids[i]; } if (scores[i] < min) { min = scores[i]; minID = ids[i]; }

11 11 mean = (1.0/numOfStudents) * sum; System.out.println("Quiz Scores and statistics."); for (i = 0; i < numOfStudents; i++) System.out.println(ids[i] +"\t"+ scores[i]); System.out.println("\nNumber of Students in the Class: " + numOfStudents); System.out.println("\nClass Average: " + mean); System.out.println("\nMinimum Score of: " + min + " is scored by the person with ID " + minID); System.out.println("\nMaximum Score of: " + max + " is scored by the person with ID " + maxID); System.out.println("\n\nList of students below average"); for (i=0; i<numOfStudents; i++) if (scores[i]<mean) System.out.println(ids[i]+"\t"+scores[i]); } )

12 12 More examples: Printing students below average in a quiz (cont’d) Sample Output Quiz Scores and Statistics. 111111 7.75 222222 6.5 333333 8.25 444444 5.25 555555 2.5 666666 9.5 777777 5.0 888888 6.5 Number of Students in the Class: 8 Class Average: 6.40625 Minimum Score of: 2.5 is scored by the person with ID 555555 Maximum Score of: 9.5 is scored by the person with ID 666666 List of All students below average 444444 5.25 555555 2.5 777777 5.0

13 13 Array cloning l The following example shows how we may make a copy of an array. class ArrayCloningExample { private static final int ELEMENTS = 5; public static void main (String[] args) { int[] a = new int[ELEMENTS]; int[] b; int i; //fill the i-th element of a with i^2 and print System.out.println("Contents of a[]"); for(i = 0; i < a.length; i++) { a[i] = i * i; System.out.println("i = "+i+" a["+i+"]=\t“ + a[i]); } // duplicate the array a into b b = (int []) a.clone(); // print out the array b System.out.println("Contents of b[] immediately after duplication from a[]"); for(i = 0; i < b.length; i++) System.out.println("i = "+i+" b[" +i+ "] =\t“ + b[i]); // Modify the array b by doubling every element for(i = 0; i < b.length; i++) b[i] *= 2;

14 14 Array cloning (cont’d) System.out.println("Contents of a[] and b[] after doubling elements of b[]"); for(i = 0; i < ELEMENTS; i++) System.out.println("i = " + i + " a[" + i + "] =\t"+a[i]+"\t\tb[" + i + "] =\t" + b[i]); } Sample Output: Contents of a[] i = 0 a[0] = 0 i = 1 a[1] = 1 i = 2 a[2] = 4 i = 3 a[3] = 9 i = 4 a[4] = 16 Contents of b[] immediately after duplication from a[] i = 0 b[0] = 0 i = 1 b[1] = 1 i = 2 b[2] = 4 i = 3 b[3] = 9 i = 4 b[4] = 16 Contents of a[] and b[] after doubling elements of b[] i = 0 a[0] = 0 b[0] = 0 i = 1 a[1] = 1 b[1] = 2 i = 2 a[2] = 4 b[2] = 8 i = 3 a[3] = 9 b[3] = 18 i = 4 a[4] = 16 b[4] = 32


Download ppt "1 Modelling 1-D Array Overview l Why do we need 1-D array l 1-D array declaration and Initialization l Accessing elements of a 1-D array l Passing Array."

Similar presentations


Ads by Google