Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Chapter 7: Arrays In this chapter, you will learn about
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Arrays Chapter 6 Chapter 6.
1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Selection Sort -Reading p Reading p
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CS102--Object Oriented Programming Lecture 5: – Arrays – Sorting: Selection Sort Copyright © 2008 Xiaoyan Li.
Arrays CS Feb Announcements Exam 1 Grades on Blackboard Project 2 scores: end of Class Project 4, due date:20 th Feb –Snakes & Ladders Game.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 4 l Class and Method Definitions l Information Hiding and Encapsulation.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Linear Search Binary Search ; Reading p Selection Sort ; Reading p
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Chapter 8 Arrays and Strings
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Arrays Chapter 6 Array Basics Arrays in Classes and Methods
Sorting Arrays. Selection Sort  One of the easiest ways to sort the elements of an array is by using the selection sort algorithm.  Assume that the.
Intro to CS – Honors I Basic Sorting GEORGIOS PORTOKALIDIS
Java Unit 9: Arrays Declaring and Processing Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Introduction To Scientific Programming Chapter 6 – Arrays.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
Chapter 10Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 10 l Array Basics l Arrays in Classes and Methods l Programming.
1 Week 9 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays Arrays.
Lecturer: Dr. AJ Bieszczad Chapter 6 COMP 150: Introduction to Object-Oriented Programming 6-1 l Array Basics l Arrays in Classes and Methods l Programming.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
CSEB114: PRINCIPLE OF PROGRAMMING Chapter 8: Arrays.
1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Chapter 8 Arrays and Strings
Chapter 61 Arrays Chapter 6. 2 Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
ARRAY Prepared by MMD, Edited by MSY1.  Introduction to arrays  Declaring arrays  Initializing arrays  Examples using arrays  Relationship with pointers.
Chapter 10. Arrays Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Computer Programming with JAVA.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Lecture 18/19 Arrays COMP1681 / SE15 Introduction to Programming.
Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.
Chapter 6 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays ** ** multidimensional.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Multidimensional Arrays l Vectors Multidimensional Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Chapter 13 Interfaces and Inner Classes Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays Chapter 7.
EKT472: Object Oriented Programming
Arrays Chapter 6 Array Basics Arrays in Classes and Methods
Searching and Sorting Linear Search Binary Search ; Reading p
Introduction To Programming Information Technology , 1’st Semester
Programming with Arrays 2
Arrays.
Presentation transcript:

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays Arrays

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 2 Announcements/Reminders l Exam 1 »Returned today at end of class l Project 4: due Thursday, Feb. 24 at 10:30 pm.

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 3 Creating Arrays l General syntax for declaring an array: BaseType[] arrayName = new BaseType[length]; Examples: 80-element array with base type char : char[] symbol = new char[80]; 100-element array of double s: double[] reading = new double[100]; 75-element array of Species : Species[] specimen = new Species[75];

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 4 Creating Arrays vs. Creating Objects l The array declaration reserves enough space in memory to hold 100 doubles. l The object declaration reserves enough space in memory to hold all the instance fields and methods of a single Automobile object. The variable reading stores the memory address of the beginning of the array. The variable myCar stores the memory address of the beginning of the object. However, you must still initialize the individual doubles in the reading array! ( myCar is initialized after executing the above statement!) double reading = new double[100]; Automobile myCar = new Automobile(“Ford”);

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 5 Array Length Length of an array is specified by the number in brackets when it is created with new »it determines the amount of memory allocated for the array elements (values) »it determines the maximum number of elements the array can hold –storage is allocated whether or not the elements are assigned values The array length can be read with the instance variable length, e.g. the following code displays the number 20 (the size, or length of the Species array, entry ): Species[] entry = new Species[20]; System.out.println(entry.length); The length attribute is established in the declaration and cannot be changed unless the array is redeclared length is used like an instance variable – it is not a method call! »Do not say entry.length()

This excerpt from the Sales Report program in the text uses the SalesAssociate class to create an array of sales associates: public void getFigures() { System.out.println(“Enter number of sales associates:”); int numberOfAssociates = SavitchIn.readLineInt(); SalesAssociate [] record = new SalesAssociate[numberOfAssociates]; int i; for (i = 0; i < numberOfAssociates; i++) { record[i] = newSalesAssociate(); System.out.println(“Enter data for associate “ + (i + 1)); record[i].readInput(); System.out.println(); } Arrays, Classes, and Methods each array element is a SalesAssociate instance variable use the readInput method of SalesAssociate An array of a class can be declared and the class's methods applied to the elements of the array. create an array of SalesAssociate s initialize each object! (otherwise they are all null!)

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 7 When Can a Method Change an Indexed Variable Argument? Remember: l primitive types are call-by-value »only a copy of the value is passed as an argument in a method call »so the method cannot change the value of the indexed variable l class types are reference types; they pass the address of the object when they are an argument in a method call »the corresponding argument in the method definition becomes another name for the object »the method has access to the actual object »so the method can change the value of the indexed variable if it is a class (and not a primitive) type

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 8 Example: An Array as an Argument in a Method Call public static void main (String [] args) { double[] grades = new double[250]; grades[0] = 80; … curveGrades(grades); System.out.println(grades[0]); // Prints 90 … } public static void curveGrades(double[] a) { int i; for(i = 0; i < a.length; i++) grades[i] = grades[i] ; }

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 9 Methods that Return an Array l Yet another example of passing a reference l Actually, the array is not passed, the address of the array is passed l The local array name within the method is just another name for the original array l newArray is not garbage collected, because c is pointing to it! c, newArray, and the return type of vowels are all the same type: char []

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 10 Gotcha : Returning an Array Instance Variable l Access methods that return references to array instance variables cause problems for information hiding. Example: Even though entry is declared private, a method outside the class can get full access to it by using getEntryArray. l In most cases this type of method is not necessary anyhow. l If it is necessary, make the method return a copy of the array instead of returning a reference to the actual array. public String[] getEntryArray() { return entry; }

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 11 Sorting an Array l Sorting a list of elements is another very common problem (along with searching a list) »sort numbers in ascending order »sort numbers in descending order »sort strings in alphabetic order »etc. l There are many ways to sort a list, just as there are many ways to search a list l Selection sort »one of the easiest »not the most efficient, but easy to understand and program

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 12 Selection Sort Algorithm for an Array of Integers To sort an array of integers in ascending order: l search the array for the smallest number and record its index l swap (interchange) the smallest number with the first element of the array »the sorted part of the array is now the first element »the unsorted part of the array is the remaining elements l search the remaining unsorted part of the array for the next smallest element and record that element's index l swap the next smallest element with the second element of the array l repeat the search and swap until all elements have been placed »each iteration of the search/swap process increases the length of the sorted part of the array by one, and reduces the unsorted part of the array by one

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 13 /************************************************** *Precondition: *Every indexed variable of the array a has a value. *Action: Sorts the array a so that *a[0] <= a[1] <=... <= a[a.length - 1]. **************************************************/ public static void sort(int[] a) { int index, indexOfNextSmallest; for (index = 0; index < a.length - 1; index++) {//Place the correct value in a[index]: indexOfNextSmallest = indexOfSmallest(index, a); interchange(index,indexOfNextSmallest, a); //a[0] <= a[1] <=...<= a[index] and these are //the smallest of the original array elements. //The remaining positions contain the rest of //the original array elements. } Selection Sort Code

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 14 /** Returns the index of the smallest value among a[startIndex], a[startIndex+1],... a[a.length-1] */ private static int indexOfSmallest (int startIndex, int[] a) { int min = a[startIndex]; int indexOfMin = startIndex; int index; for (index = startIndex + 1; index < a.length; index++) { if (a[index] < min) { min = a[index]; indexOfMin = index; // min is smalest of a[startIndex] through a[index] } return indexOfMin; }

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 15 /** Precondition: i and j are valid indices for the array a. Postcondition: Values of a[i] and a[j] have been interchanged. */ private static void interchange (int i, int j, int[] a) { int temp; temp = a[i]; a[i] = a[j]; a[j] = temp; // original value of a[i] }

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 16 Example: Selection Sort The SelectionSort program in the text shows a class for sorting an array of int s in ascending order l Notice the precondition: every indexed variable has a value l Also notice that the array may have duplicate values and the class handles them in a reasonable way - they are put in sequential positions l Finally, notice that the problem was broken down into smaller tasks, such as "find the index of the smallest value" and "interchange two elements" »these subtasks are written as separate methods and are private because they are helper methods (users are not expected to call them directly)

Selection Sort: Diagram of an Example Problem: sort this 10-element array of integers in ascending order: 1st iteration: smallest value is 3, its index is 4, swap a[0] with a[4] before: after: 2nd iteration: smallest value in remaining list is 5, its index is 6, swap a[1] with a[6] Etc. - only nine iterations are required since the last one will put the last two entries in place by swapping them if necessary. Key: smallest remaining value sorted elements Chapter 10Java: an Introduction to Computer Science & Programming - Walter Savitch 17

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 18 Multidimensional Arrays l Arrays with more than one index »number of dimensions = number of indexes l Arrays with more than two dimensions are a simple extension of two-dimensional (2-D) arrays l A 2-D array corresponds to a table or grid »one dimension is the row »the other dimension is the column »cell: an intersection of a row and column »an array element corresponds to a cell in the table

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 19 Table as a 2-Dimensional Array l The table assumes a starting balance of $1000 l First dimension: row identifier - Year l Second dimension: column identifier - percentage l Cell contains balance for the year (row) and percentage (column) l Balance for year 4, rate 7.00% = $1311 Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 19

Table as a 2-D Array l Generalizing to two indexes: [row][column] l First dimension: row index l Second dimension: column index l Cell contains balance for the year/row and percentage/column l All indexes use zero-numbering »table[3][4] = cell in 4th row (year = 4) and 5th column (7.50%) »table[3][4] = $1311 (shown in yellow) Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 20 Row Index 3 (4th row) Column Index 4 (5th column)

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 21 Java Code to Create a 2-D Array l Syntax for 2-D arrays is similar to 1-D arrays Declare a 2-D array of int s named table »the table should have ten rows and six columns int[][] table = new int[10][6];

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 22 Method to Calculate the Cell Values Each array element corresponds to the balance for a specific number of years and a specific interest rate (assuming a starting balance of $1000): balance(starting, years, rate) = (starting) x (1 + rate) years The repeated multiplication by (1 + rate) can be done in a for loop that repeats years times. balance method in class InterestTable

Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 23 Processing a 2-D Array: for Loops Nested 2-Deep Arrays and for loops are a natural fit To process all elements of an n -D array nest n for loops »each loop has its own counter that corresponds to an index l For example: calculate and enter balances in the interest table »inner loop repeats 6 times (six rates) for every outer loop iteration »the outer loop repeats 10 times (10 different values of years ) »so the inner repeats 10 x 6 = 60 times = # cells in table Excerpt from main method of InterestTable