name: inverse layout: true class: taylor msoe --- class: center, middle .title[ # Arrays ] ??? Toggle speaker view by pressing P Pressing C clones the slideshow view, which is the view to put on the projector if you're using speaker view. Press ? to toggle keyboard commands help. --- # Arrays * A way to store a group of the same-typed values -- * A way of parameterizing a variable name -- * Suppose we have three quiz scores stored as `int`s ``` Java int sum = quiz1 + quiz2 + quiz3; int average = (quiz1 + quiz2 + quiz3) / 3.0; ``` -- * What if we have 100 quiz scores? --- # Array Basics * We declare an array reference as `int[] array` -- * The array has one property: `array.length` -- * Here we set `array` to point to an array literal: ``` Java array = {1, 2, 3, 4}; ``` -- * Alternatively, we can allocate space for an array: ``` Java array = new int[4]; ``` --- # Accessing Elements * We access elements with the subscript operator ``` Java int[] array = new int[4]; array[0] = 1; array[1] = 2; array[2] = array[1] + 1; array[3] = array.length; ``` -- * The array now contains: 1, 2, 3, 4 -- * `array` is a parameterized variable name that uses the `[ ]` operator to select specific value --- # Examples ``` Java private static int sum(int[] scores) { int sum = 0; for (int i = 0; i < scores.length; i++) { sum += scores[i]; } return sum; } // scores.length must be greater than zero private static double average(int[] scores) { int sum = 0; for (int i = 0; i < scores.length; i++) { sum += scores[i]; } return (double)sum / scores.length; } ``` --- # Notes * You must use a valid parameter when subscripting, e.g., `array[-2]` will crash your program -- * Can have arrays of primitives or of references + `int[] integers = new int[5];` + `String[] words = new String[5];` -- * Initial value for primitives is `0`, for references is `null` -- * Arrays cannot be resized --- # Adding a value to an array ``` Java // Returns an array that is one longer than words containing // word at the last position in the returned array private static String[] add(String[] words, String word) { String[] bigger = new String[words.length + 1]; for (int i = 0; i < words.length; i++) { bigger[i] = words[i]; } bigger[bigger.length - 1] = word; return bigger; } ``` --- # Enhanced for loop ``` Java private static int sum(int[] scores) { int sum = 0; for (int score : scores) { // Equivalent sum += score; } return sum; } ``` -- ``` private static int sum(int[] scores) { int sum = 0; for (int i = 0; i < scores.length; i++) { // Equivalent int score = scores[i]; // Equivalent sum += score; } return sum; } ```