1 / 44

Computer Science I Arrays Professor: Evan Korth New York University

Computer Science I Arrays Professor: Evan Korth New York University. Road Map. What is an Array? Parts of an Array Elements, Indexes, Subscripts, etc. Declaring Arrays Initializing Arrays Examples Passing arrays to methods Reading, Chapter 6, Sections 6.1 – 6.4. What is an Array?.

storm
Télécharger la présentation

Computer Science I Arrays Professor: Evan Korth New York University

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Computer Science IArraysProfessor: Evan KorthNew York University

  2. Road Map • What is an Array? • Parts of an Array • Elements, Indexes, Subscripts, etc. • Declaring Arrays • Initializing Arrays • Examples • Passing arrays to methods • Reading, Chapter 6, Sections 6.1 – 6.4

  3. What is an Array?

  4. What is an Array? • An array is a collection of variables. • Arrays have three important properties: • arrays represent a group of related data (for example, temperature for the last five days, or stock prices for the last 30 days.) • all data within a single array must share the same data type (for example, you can create an array of ints or an array of floats, but you cannot mix and match ints with floats.) • The size of an array is fixed once it is created.

  5. What exactly are we talking about?! • Let’s say you have ten students and you want to save the grades for each of them for use throughout your program (i.e. we need to remember every grade not just loop and count them or average them, etc.) • Could do it the hard way: • Set up ten variables called studentOneGrade, studentTwoGrade, studentThreeGrade, etc. • Very difficult to use and manipulate • Instead, could use an array to do it the easy way…

  6. Using an array variable • Create an array variable called studentGrades[10] • Declared as follows: • int studentGrades[] = new int[10]; • This sets up a location in memory for 10 integers which can be referenced using studentGrades[ # ] where # is the particular student you want to look at.

  7. Array Naming Considerations • The rules for naming variables apply when selecting array variable names • Composed of letters, digits, dollar signs and underscore characters • Cannot start with a digit • Follow all the good programming hints recommended for variable names • i.e. just think of it as an ordinary variable when making up the name • In addition it is bad style to end an array name with a digit • ie. array3[5]

  8. Parts of an Array

  9. Parts of the array • The array has some terminology we haven’t seen yet • Elements • Index • Position Number • Subscript • Zeroth element • Keyword “new”

  10. Elements • Refers to the individual items represented by the array. For example, • an array of 10 integers is said to have 10 elements • an array of 15 floats has 15 elements • an array of 5 characters has 5 elements • and so on…

  11. Index (Position Number or Subscript) • Refers to one particular element in the array • Also known as position number or, more formally, as a subscript • The first element in an array is represented by an index or subscript of 0 (zero). For example, • studentGrades[ 0 ] • This first position is known as the zeroth element • The second position is referred to by • studentGrades[ 1 ]

  12. Index 0 1 2 3 4 5 6 7 8 9 Value 85 76 99 38 78 98 89 90 82 88 Figuring out the array positions • In Java, an arrays’ elements start out at index 0 and go up to (the number of elements – 1) • For example, our array of 10 student grades filled in with grades might look like:

  13. Array positions (cont’d) • We can access them by specifying the array name followed by square brackets with the index number between them. For example, System.out.println ("The third student’s grade is " + studentGrades[ 2 ] ); • Would print only the third integer spot in the array (remember 0 is the first, 1 is the second, and 2 is the third element’s index / subscript) • The output would look like the following: The third student’s grade is 99

  14. Array positions (cont’d) • The index scheme starting at 0 may be initially confusing. • This is the cause of many off-by-one errors so study the concept carefully • The element in the array’s first position is sometimes referred to as the zeroth element. • Notice the difference between "position" and "element number"

  15. subscript terminology • From this point forward, for this class, all references to array elements will refer to the subscript of the array. • In the event that we want to discuss the position of an element in an array, we will refer to it’s position. • In other words, we will not use i'th element or element i notation unless we are referring to the zeroth element.

  16. Keyword new • As we have seen, the keyword new is used in Java when you wish to create a new object. • In Java, arrays are objects. • As with all data members of objects, the elements of the each position in a new array will automatically be initialized to the default value for the array’s type.

  17. Some powerful features of arrays • Can use expressions as the subscript • E.g. if variables a = 1 and b = 2 • studentGrades[ a + b ] would be the same as writing studentGrades[ 3 ] • Can use array elements in expressions • E.g. int gradeTotal = 0 ; gradeTotal = studentGrades[ 0 ] + studentGrades[ 1 ] + studentGrades[ 2 ] + …etc… studentGrades[ 9 ] ; • Would add up all the array elements and store them in gradeTotal.

  18. Powerful features (cont’d) • Can set array elements equal to other values or expressions. For example, studentGrades[ 1 ] = 100 ; • This would set the array element with a subscript of 1 to a grade of 100. That is, the second student would have a grade of 100. • Java allows us to access an array’s length by using the following notation: • studentGrades.length would evaluate to 10

  19. Using Arrays

  20. So how do we use arrays? • Same concepts as other variables apply • Must declare the array • Must initialize the array (unlike regular variables, Java will initialize arrays with default values) • Arrays variables are actually reference variables. • Can use arrays in expressions and methods, setting elements’ values or using their values, similar to the use of ordinary variables

  21. Declaring an array • First you can declare an array reference variable (you must specify the type of the elements in the array) : • int [] myFirstArray; //declares an array //variable for ints • Note: the line above does not allocate memory for the array (it cannot since we have not said the size of the array yet). It only sets aside enough memory to reference the array. Until we create an array, the reference is to null. • Next, we create the array and “point” the reference to it: • myFirstArray = new int [10]; • To create the array, we need the number of elements in the array so the computer can set aside adequate memory for the array. • We can combine the declaration and allocation lines into one line as follows: • int [] myFirstArray = new int [10];

  22. Declaring arrays (cont) • You can use a constant to set the size of the array final int GRID_ROWS_MAX 8 int [] gridRows = new int [ GRID_ROWS_MAX ]; • In java, you do not need to know the size of the array at COMPILE time. Instead you can know the size at RUN time. For example, the following is legal: inputString = JOptionPane.showInputDialog ("How many students ?"); int students = Integer.parseInt (inputString); int [] myFirstArray = new int [students];

  23. Initializing an Array • You can initialize an array when you declare it, as you do with other variables • Syntax is slightly different, as you are now initializing more than one element at a time • One way at declaration, using initializers: int myFirstArray[ ] = { 0, 0, 0, 0, 0 }; • Note the braces around the initial zeroes which themselves are separated by commas. • Also note that creating arrays in this way eliminates the need for the keyword new.

  24. Initializing array with a for loop • After declaring an array, you can initialize it in the body of your program by using a for loop: int [] myFirstArray = new int [ 5 ]; for (int i = 0 ; i <= 4 ; i++ ) { myFirstArray[ i ] = 1 ; } // end for • Note the upper bound is 4, not 5! That is, you loop through 0 to 4 to initialize an array with 5 elements • Note: Array elements are initialized with default values. Numeric types get 0, boolean get false and char gets the null character (ascii code 0).

  25. Accessing elements with for loop • Can use a for loop to print the contents of an array int [] myFirstArray = new int [ 5 ]; for (int i = 0 ; i <= myFirstArray.length – 1; i++ ) { System.out.println ("array element " + i + " is equal to " + myFirstArray [i]); } // end for • Note the use of myFirstArray.length instead of using the size itself. It is better style to do so. Why?

  26. Array Bounds • Very Important: Java does not provide array bounds checking at compile time. • This means that your program will crash at run time of you try to access memory outside of an array’s bounds. • For example, suppose you have: int [] myFirstArray = new int [ 10 ]; myFirstArray[100] = 45; • 100 is very far outside your defined size (0..9) • However, the compiler will not indicate an error.

  27. 7.4 Examples Using Arrays • Using histograms do display array data graphically • Histogram • Plot each numeric value as bar of asterisks (*)

  28. Declare array with initializer list For each array element, print associated number of asterisks 1 // Fig. 7.6: Histogram.java 2 // Histogram printing program. 3 import javax.swing.*; 4 5 public class Histogram { 6 7 public static void main( String args[] ) 8 { 9 int array[] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; 10 11 String output = "Element\tValue\tHistogram"; 12 13 // for each array element, output a bar in histogram 14 for ( int counter = 0; counter < array.length; counter++ ) { 15 output += "\n" + counter + "\t" + array[ counter ] + "\t"; 16 17 // print bar of asterisks 18 for ( int stars = 0; stars < array[ counter ]; stars++ ) 19 output += "*"; 20 21 } // end outer for 22 23 JTextArea outputArea = new JTextArea(); 24 outputArea.setText( output ); 25 Histogram.javaLine 9Declare array with initializer list Line 19For each array element, print associated number of asterisks

  29. 26 JOptionPane.showMessageDialog( null, outputArea, 27 "Histogram Printing Program", JOptionPane.INFORMATION_MESSAGE ); 28 29 System.exit( 0 ); 30 31 } // end main 32 33 } // end class Histogram Histogram.java

  30. 7.4 Examples Using Arrays (Cont.) • Using the elements of an array as counters • Use a series of counter variables to summarize data

  31. Declare frequency as array of 7ints Generate 6000 random integers in range 1-6 Increment frequency values at index associated with random number 1 // Fig. 7.7: RollDie.java 2 // Roll a six-sided die 6000 times. 3 import javax.swing.*; 4 5 public class RollDie { 6 7 public static void main( String args[] ) 8 { 9 int frequency[] = new int[ 7 ]; 10 11 // roll die 6000 times; use die value as frequency index 12 for ( int roll = 1; roll <= 6000; roll++ ) 13 ++frequency[ 1 + ( int ) ( Math.random() * 6 ) ]; 14 15 String output = "Face\tFrequency"; 16 17 // append frequencies to String output 18 for ( int face = 1; face < frequency.length; face++ ) 19 output += "\n" + face + "\t" + frequency[ face ]; 20 21 System.out.println(”Rolling a Die 6,00 times” ); 22 23 24 System.out.println ( output ); 25 26 27 System.exit( 0 ); 28 29 } // end main 30 31 } // end class RollDie RollDie.javaLine 9Declare frequency as array of 7ints Lines 12-13Generate 6000 random integers in range 1-6Line 13Increment frequency values at index associated with random number

  32. 7.4 Examples Using Arrays (Cont.) • Using arrays to analyze survey results • 40 students rate the quality of food • 1-10 Rating scale: 1 mean awful, 10 means excellent • Place 40 responses in array of integers • Summarize results

  33. Declare responses as array to store 40 responses Declare frequency as array of 11int and ignore the first element For each response, increment frequency values at index associated with that response 1 // Fig. 7.8: StudentPoll.java 2 // Student poll program. 3 import javax.swing.*; 4 5 public class StudentPoll { 6 7 public static void main( String args[] ) 8 { 9 int responses[] = { 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6, 10 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6, 11 4, 8, 6, 8, 10 }; 12 int frequency[] = new int[ 11 ]; 13 14 // for each answer, select responses element and use that value 15 // as frequency index to determine element to increment 16 for ( int answer = 0; answer < responses.length; answer++ ) 17 ++frequency[ responses[ answer ] ]; 18 19 String output = "Rating\tFrequency\n"; 20 21 // append frequencies to String output 22 for ( int rating = 1; rating < frequency.length; rating++ ) 23 output += rating + "\t" + frequency[ rating ] + "\n"; 24 JOpSystem.out.println( output ); 25 26 System.exit( 0 ); 27 28 } // end main 29 30 } // end class StudentPoll StudentPoll.javaLines 9-11Declare responses as array to store 40 responses Line 12Declare frequency as array of 11int and ignore the first elementLines 16-17For each response, increment frequency values at index associated with that response

  34. StudentPoll.java

  35. 7.4 Examples Using Arrays (Cont.) • Some additional points • When looping through an array • Index should never go below 0 • Index should be less than total number of array elements • When invalid array reference occurs • Java generates ArrayIndexOutOfBoundsException • We will discuss Java’s exception handling later this semester

  36. 7.5 References and Reference Parameters • Two ways to pass arguments to methods • Pass-by-value • Copy of argument’s value is passed to called method • In Java, every primitive is pass-by-value • Pass-by-reference • Caller gives called method direct access to caller’s data • Called method can manipulate this data • Improved performance over pass-by-value • In Java, every object is simulated pass-by-reference • In Java, arrays are objects • Therefore, arrays are passed to methods by reference • Technically, we are using pass by value but the “value” we are passing is a reference to the array.

  37. 7.6 Passing Arrays to Methods • To pass array argument to a method • Specify array name without brackets • Array hourlyTemperatures is declared as int hourlyTemperatures = newint[ 24 ]; • The method call modifyArray( hourlyTemperatures ); • Passes array hourlyTemperatures to method modifyArray

  38. Passing arrays to methods (cont) • In the method header, use similar syntax as that for array declaration: public static void passArray (int array [] ) or public static void passArray (int [] array )

  39. Returning arrays from methods • We have seen examples of methods that modify an array. Since the array is passed by reference, it is modified in the original method as well. • Another way to return information in an array is to explicitly return the array. • For example, a method with the header: public static int [] makeArray () • Returns an integer array.

  40. Returning arrays (cont) • In order to return an array, the method creates the array first. public static int [] makeArray () { int [] myArray = new int [10]; for (int i; i < myArray.length; i++) Myarray [i] = i; return myArray; } • The method above creates a new array called myArray, initializes each element and returns the reference to myArray.

  41. Example 5.6 (Liang)Copying Arrays In this example, you will see that a simple assignment cannot copy arrays in the following program. The program simply creates two arrays and attempts to copy one to the other, using an assignment statement.

  42. Copying Arrays (Liang)

  43. Copying Arrays (Liang) Using a loop: int[] sourceArray = {2, 3, 1, 5, 10}; int[] targetArray = new int[sourceArray.length]; for (int i = 0; i < sourceArrays.length; i++) targetArray[i] = sourceArray[i];

  44. The arraycopy Utility (Liang) arraycopy(sourceArray, src_pos, targetArray, tar_pos, length); Example: System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);

More Related