1 / 29

Introduction to Arrays

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 Specifies the type and the name

qamra
Download Presentation

Introduction to Arrays

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. Introduction to Arrays CSCI 142 Object Oriented Programming Tina Ostrander

  2. An array… • A group of variables that… • Have a name • Have a single type • Primitive types • Object types • Can hold many values

  3. Creating an Array • Declare the array variable • Specifies the type and the name • Allocate memory for the array • Specifies the size • Initialize the array elements • Fills the array with values

  4. Creating an Array • Declare the array variable • double[] salary; • Allocate memory for the array • salary = new double[5]; • Initialize the array elements • salary[0] = 32500; Note: Steps 1 and 2 may be combined: double[] salary = new double[5]; Create a double array called salary Allocate enough memory to store 5 elements Assigns a value to the 1st array element

  5. Creating an Array • Declare the array variable • GOval[] circles; • Allocate memory for the array • circles = new GOval[5]; • Initialize the array elements • circles[0] = new GOval(50, 50); Note: Steps 1 and 2 may be combined: GOval[] circles = new GOval[5]; Create a GOval array called circles Allocate enough memory to store 5 elements Assigns an object to the 1st array element

  6. 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;

  7. 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];

  8. 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

  9. 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);

  10. 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; orage[age.length - 1] = 45;

  11. 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

  12. 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 onlyworks when there isa pattern to the values.

  13. Initializing an Array • An array can be initialized with a loop GOval[] circles = new GOval[10];int size = 25;for (int i = 0; i < circles.length; i++){ circles[i] = new GOval(size, size); size += 25;} This returns the numberof elements in the array.

  14. Example 2 String months = "JanFebMarAprMayJunJulAugSepOctNovDec"; String[] month = new String[12]; for (inti = 0; i < 12; i++) month[i] = months.substring(i * 3, i * 3 + 3); Example 3 intcount = 0; double[] cost = new double[5]; while (count < cost.length) { cost[count] = readDouble(“Enter cost”); count++; } Initializing an Array

  15. 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 (inti = 0; i<squares.length; i++) squares[i] = new GRect(50, 50);

  16. Practice Q: Assign even numbers 2 through 10 to the age array. A: for (inti = 0; i < age.length; i++) age[i] = i * 2 + 2; A: intval = 2; for (inti = 0; i < age.length; i++) { age[i] = val; val += 2; }

  17. Practice Q: Assign the numbers 5 through 1 to the age array. A: for (inti = 0; i < age.length; i++) age[i] = 5-i; A: intval = 5; for (inti = 0; i < age.length; i++) { age[i] = val; val--; }

  18. Practice Q: Assign a GRect to each element of the squares array, where each square is 10 pixels larger than the previous square . A: intsize = 10;for (inti = 0; i < squares.length; i++) { squares[i] = new GRect(size, size); size += 10; }

  19. 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

  20. 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

  21. public class Search extends ConsoleProgram { public void run() { int[] nums = {15, 9, 6, 2, 4, 7, 23, 18, 29, 18}; intfindNum = 7, position = -1; for (inti = 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."); } }

  22. Try It • Modify the Search program so that it displays every instance of findNum.

  23. 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

  24. 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(inti=0; i<array.length; i++) { sum += array[i]; } return sum / array.length; } }

  25. Try It • Add a maximum method to the Salary program. • The method should take an array and return the largest value in the array.

  26. 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.

  27. 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

  28. 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; } for (int i = 0; i < salary.length; i++) print (salary[i] + "\t"); println(); This sorts ints

  29. 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

More Related