Introduction to Arrays CSCI 142 Object Oriented Programming Tina Ostrander An array… A group of variables that… • Have a name • Have a single type • Primitive types • Object types • Can hold many values Creating an Array Declare the array variable 1. • Specifies the type and the name Allocate memory for the array 2. • Specifies the size Initialize the array elements 3. • Fills the array with values Creating an Array 1. Declare the array variable 2. Create a double array called salary Allocate memory for the array 3. double[] salary; salary = new double[5]; Allocate enough memory to store 5 elements Initialize the array elements salary[0] = 32500; Assigns a value to the 1st array element Note: Steps 1 and 2 may be combined: double[] salary = new double[5]; Creating an Array 1. Declare the array variable 2. Create a GOval array called circles Allocate memory for the array 3. GOval[] circles; circles = new GOval[5]; Allocate enough memory to store 5 elements Initialize the array elements circles[0] = new GOval(50, 50); Assigns an object to the 1st array element Note: Steps 1 and 2 may be combined: GOval[] circles = new GOval[5]; Practice Q: Write a statement to declare an int array called age. A: int[] age; Q: Write a statement to declare a GRect array called squares. A: GRect[] squares; Practice Q: Allocate memory for 5 elements in the age array. A: age = new int[5]; Q: Allocate memory for 10 elements in the squares array. A: squares = new GRect[10]; Memory allocation Memory is allocated for each element in the array. • Try to accurately estimate the number of array elements. • A value does not need to be stored in each array element. • The length field contains the size of the array. Elements are initialized • Numbers to zero • Objects to null • Booleans to false Initializing an Array Array elements can be initialized one at a time… double[] salary = new double[5]; salary[0] = 30000.00; salary[1] = 45000.00; salary[2] = 52500.00; salary[3] = 62250.00; salary[4] = 37500.00; GOval[] circles = new GOval[5]; circles[0] = new GOval(50, 50); circles[1] = new GOval(75, 75); circles[2] = new GOval(100, 100); circles[3] = new GOval(125, 125); circles[4] = new GOval(150, 150); Practice Q: Assign the value of 20 to the first element of the age array. A: age[0] = 20; Q: Assign the value of 45 to the last element of the age array. A: age[4] = 45; or age[age.length - 1] = 45; Initializing an Array An array can be initialized with an “initializer list”… double[] salary = {30000, 45000, 52500, 62250, 37500}; String[] name = {“Branco”, “Tierney”, “Matt”}; • Array is declared, memory is allocated, and elements are initialized all in one statement • Size is automatically assigned • Semicolon is required after closing brace • Keyword new is not required • This only works if you know the array values when the array is declared Initializing an Array An array can be initialized with a loop… double[] salary = new double[10]; double amount = 40000.00; for (int i = 0; i < salary.length; i++) { salary[i] = amount; amount += 10000; } Note that this only works when there is a pattern to the values. Initializing an Array An array can be initialized with a loop This returns the number of elements in the array. GOval[] circles = new GOval[10]; int size = 25; for (int i = 0; i < circles.length; i++) { circles[i] = new GOval(size, size); size += 25; } Initializing an Array Example 2 String months = "JanFebMarAprMayJunJulAugSepOctNovDec"; String[] month = new String[12]; for (int i = 0; i < 12; i++) month[i] = months.substring(i * 3, i * 3 + 3); Example 3 int count = 0; double[] cost = new double[5]; while (count < cost.length) { cost[count] = readDouble(“Enter cost”); count++; } Practice Q: Assign a GRect object to the first element of the squares array. A: squares[0] = new GRect(50, 50); Q: Assign a GRect to each element of the squares array. A: for (int i = 0; i<squares.length; i++) squares[i] = new GRect(50, 50); Practice Q: Assign even numbers 2 through 10 to the age array. A: for (int i = 0; i < age.length; i++) age[i] = i * 2 + 2; A: int val = 2; for (int i = 0; i < age.length; i++) { age[i] = val; val += 2; } Practice Q: Assign the numbers 5 through 1 to the age array. A: for (int i = 0; i < age.length; i++) age[i] = 5-i; A: int val = 5; for (int i = 0; i < age.length; i++) { age[i] = val; val--; } Practice Q: Assign a GRect to each element of the squares array, where each square is 10 pixels larger than the previous square . A: int size = 10; for (int i = 0; i < squares.length; i++) { squares[i] = new GRect(size, size); size += 10; } Try It Create a ConsoleProgram Declare an array called grades Allocate enough memory for 5 grades Initialize the array by prompting the user to enter each grade Calculate the average grade Searching an Array Loop through the array Compare search value to each value in the array Use a variable to keep track of if/where the search value was found public class Search extends ConsoleProgram { public void run() { int[] nums = {15, 9, 6, 2, 4, 7, 23, 18, 29, 18}; int findNum = 7, position = -1; for (int i = 0; i < nums.length; i++) if (nums[i] == findNum) { position = i; break; //Quit looking } if (position != -1) println (findNum + " found at position " + position); else println (findNum + " was not found."); } } Try It Modify the Search program so that it displays every instance of findNum. Passing Arrays An array variable or an entire array may be passed to a method. Array values are passed by value. myMethod(salary[3]) • Copy of the value is passed Arrays are passed by reference. myMethod(salary) • Array address is passed public class Salary extends ConsoleProgram { public void run() { double[] salary = {29000, 32500, 56000, 48500, 42950}; println ("The average salary is " + average(salary)); } public double average(double[] array) { double sum = 0.0; for(int i=0; i<array.length; i++) { sum += array[i]; } return sum / array.length; } } Try It Add a maximum method to the Salary program. The method should take an array and return the largest value in the array. Ordered Arrays An array is ordered if its values are in ascending or descending order. Ordered arrays can be searched more efficiently than unordered arrays. Sorting Arrays Bubble sort • Compare adjacent items if (someArray[i] > someArray[i + 1]) • If they are out of order, swap them temp = someArray[i]; someArray[i] = someArray[i + 1]; someArray[i + 1] = temp; • For n items, make n-1 passes through the list int[] salary = {32500, 45950, 24675, 23000, 29800}; int temp = 0; for (int i = 0; i < salary.length-1; i++) for (int j = 0; j < salary.length – i - 1; j++) if (salary[j] > salary [j + 1]) { //swap temp = salary[j]; salary[j] = salary[j + 1]; salary[j + 1] = temp; This } sorts ints for (int i = 0; i < salary.length; i++) print (salary[i] + "\t"); println(); Why use Arrays? Arrays allow for faster data access (RAM vs. storage) Data entered into an array once can be used multiple times Arrays simplify programming Arrays allow fewer variable names to be defined and used