Chapter 6: Arrays.

Slides:



Advertisements
Similar presentations
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Arrays.
Advertisements

Arrays, part 2. Array applications Arrays are useful whenever a relatively large amount of data must be kept available in memory for processing We will.
Array Basics Suppose you need to process daily temperatures for a 12-month period in a science project, would you use 365 variables? You can, but would.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Arrays Sections 1-4.
1 CS100J 13 March 2006 Arrays. Reading: Secs 8.1, 8.2, 8.3. Listen to the following lectures on loops on your Plive CD. They are only 2-3 minutes long,
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 Arrays.
Chapter 10 Arrays. Topics Declaring and instantiating arrays Array element access Arrays of objects Arrays as method parameters Arrays as return values.
1 CS100J 14 March 2006 Arrays. Reading: Secs 8.1, 8.2, 8.3. Listen to the following lectures on loops on your Plive CD. They are only 2-3 minutes long,
Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection.
بسم الله الرحمن الرحيم CPCS203: Programming II. Objectives After you have read and studied this chapter, you should be able to –Manipulate a collection.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
1 11/8/06CS150 Introduction to Computer Science 1 Arrays Chapter 8 page 477 November 13, 2006.
CS180 Recitation 25th/26th October, 2007 Department of Computer Science, Purdue University.
CS100J 17 March 2005 Arrays. Reading: Secs 8.1, 8.2, 8.3. The last Java feature to study in this course Quote for the Day: Computer science has its field.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Arrays.
Arrays Chapter 8 page /24/07CS150 Introduction to Computer Science 1 Arrays (8.1)  One variable that can store a group of values of the same.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Arrays Lists.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 10 Arrays and Collections.
1 CS100J 25 October 2006 Arrays. Reading: Secs 8.1, 8.2, 8.3. Listen to the following lectures on loops on your Plive CD. They are only 2-3 minutes long,
Chapter 8 - Arrays. Chapter 8 Common to want to deal with collection of items Common to want to deal with collection of items Keep information about all.
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Arrays : Objectives After you have read and studied this chapter, you should be able to –Manipulate a collection of data values, using an array. –Declare.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Array Basics An array is a collection of data.
Dr. Salah Hammami KSU-CCIS-CS Ahmad Al-Rjoub CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science Ahmad.
1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Most of these slides are based on “Intro to.
1 On (computational) simplicity We are trying to teach not just Java, but how to think about problem solving. Computer science has its field called computational.
Primitive Arrays A primitive array stores multiple values of the same primitive data type. rainfall The index of the first position in an.
1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides.
Arrays Adapted from materials created by Dr. Donald Bell, Cal Poly 2000 (updated February 2004)
CS1101: Programming Methodology Recitation 5 – Arrays and Collections.
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Arrays (adapted from the publisher’s.
Arrays Collections of data Winter 2004CS-1010 Dr. Mark L. Hornick 1.
1 CS Oct 2008 Arrays. Reading: Secs 8.1, 8.2, 8.3 Listen to the following lectures on loops on your Plive CD. They are only 2-3 minutes long, and.
1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Most of these slides are.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
CS1101: Programming Methodology
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Chapter VII: Arrays.
Lesson 8: Introduction To Arrays
Chapter 10 Arrays Animated Version
User-Written Functions
Java Language Basics.
Chapter 8 - Arrays.
Java Review Most of these slides are based on
Java Review: Reference Types
Objects First with Java CITS1001
Advanced Programming Behnam Hatami Fall 2017.
Arrays, Collections and Repetition Part A – Arrays and Repetition
CMSC 202 Static Methods.
Basic Files + (Chapter 10 – Arrays) : Objectives
Week 9 – Lesson 1 Arrays – Character Strings
Chapter 10 Arrays ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
© A+ Computer Science - Arrays and Lists © A+ Computer Science -
Chapter 6: Arrays.
Classes and Objects 5th Lecture
Lecture 18 Arrays and Pointer Arithmetic
Arrays and Collections
Arrays and Collections
Dynamic Data Structures and Generics
Chapter 16 Pointers and Arrays
Java Review Most of these slides are based on
Java Programming Language
Data Structures & Algorithms
Chapter 9 Array Basics Suppose you need to process daily temperatures for a 12-month period in a science project, would you use 365 variables? You can,
Classes and Objects Object Creation
2015 January February March April May June July August September
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Chapter 6: Arrays

Objectives After studying this chapter, Stdent should be able to Manipulate a collection of data values, using an array. Declare and use an array of primitive data types in writing a program. Declare and use an array of objects in writing a program Define a method that accepts an array as its parameter and a method that returns an array Describe how a two-dimensional array is implemented as an array of arrays We will cover the basic array processing in this lesson, manipulating arrays of primitive data types and objects.

Array Basics An array is a collection of data values. If your program needs to deal with 100 integers, 500 Account objects, 365 real numbers, etc., you will use an array. In Java, an array is an indexed collection of data values of the same type. Suppose you need to handle up to 300 Student objects in a program for maintaining a high school alumni list, would you use 300 variables? Suppose you need to process daily temperatures for a 12-month period in a science project, would you use 365 variables? You can, but would you? To manipulate a collection of data, we can use arrays. 11/16/2018

Arrays of Primitive Data Types Array Declaration <data type> [ ] <variable> //variation 1 <data type> <variable>[ ] //variation 2 Array Creation <variable> = new <data type> [ <size> ] Example double[ ] rainfall; rainfall = new double[12]; Variation 1 double rainfall [ ]; rainfall = new double[12]; Variation 2 As you can declare and create objects in one statement such as Person p = new Person( ); you can declare and create an array in one statement as double[ ] rainfall = new double[12]; Strictly speaking, an array is a reference data type and really an object because there is no class called Array in Java. The thumbnail note in page 413 is therefore not 100 percent accurate. An array is like an object! 11/16/2018

Accessing Individual Elements Individual elements in an array accessed with the indexed expression. double[] rainfall = new double[12]; rainfall 1 2 3 4 5 6 7 8 9 10 11 rainfall[2] This indexed expression refers to the element at position #2 The index of the first position in an array is 0. 11/16/2018

Array Processing – Sample1 double[] rainfall = new double[12]; double annualAverage, sum = 0.0; for (int i = 0; i < rainfall.length; i++) { rainfall[i] = Double.parseDouble( JOptionPane.showinputDialog(null, "Rainfall for month " + (i+1) ) ); sum += rainfall[i]; } annualAverage = sum / rainfall.length; The public constant length returns the capacity of an array. This code computes the average annual rainfall. Notice the public constant length returns the capacity, not the actual number of non-blank values in the array. 11/16/2018

Array Processing – Sample 2 double[] rainfall = new double[12]; String[] monthName = new String[12]; monthName[0] = "January"; monthName[1] = "February"; … double annualAverage, sum = 0.0; for (int i = 0; i < rainfall.length; i++) { rainfall[i] = Double.parseDouble( JOptionPane.showinputDialog(null, "Rainfall for " + monthName[i] )); sum += rainfall[i]; } annualAverage = sum / rainfall.length; The same pattern for the remaining ten months. This code also computes the average annual rainfall, but this time we use the second array, an arrray of String so the prompt becomes "Rainfall for January", "Rainfall for February", and so forth. Notice how the monthName array is used in the for loop. The actual month name instead of a number. 11/16/2018

Array Processing – Sample 3 Compute the average rainfall for each quarter. //assume rainfall is declared and initialized properly double[] quarterAverage = new double[4]; for (int i = 0; i < 4; i++) { sum = 0; for (int j = 0; j < 3; j++) { //compute the sum of sum += rainfall[3*i + j]; //one quarter } quarterAverage[i] = sum / 3.0; //Quarter (i+1) average This code computes the average rainfall for each quarter. The inner loop is used to compute the rainfall for a given quarter. The outer loop processes the four quarters. This is how the values for i, j, and 3*i+j change: i j 3*i+j 0 0 0 1 1 2 2 1 0 3 1 4 2 5 2 0 6 1 7 2 8 3 0 9 1 10 2 11 The sample code is equivalent to for (int i = 0; i < 3; i++ ) { quarterAverage[0] += rainfall[i]; quarterAverage[1] += rainfall[i+3]; quarterAverage[2] += rainfall[i+6]; quarterAverage[3] += rainfall[i+9]; } quarterAverage[0] = quarterAverage[0] / 3.0; quarterAverage[1] = quarterAverage[1] / 3.0; quarterAverage[2] = quarterAverage[2] / 3.0; quarterAverage[3] = quarterAverage[3] / 3.0; 11/16/2018

Array Initialization Like other data types, it is possible to declare and initialize an array at the same time. int[] number = { 2, 4, 6, 8 }; double[] samplingData = { 2.443, 8.99, 12.3, 45.009, 18.2, 9.00, 3.123, 22.084, 18.08 }; String[] monthName = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; When an array is initialized in this manner, its capacity is set to the number of elements in the list. number.length samplingData.length monthName.length 4 9 12 11/16/2018

Variable-size Declaration In Java, we are not limited to fixed-size array declaration. The following code prompts the user for the size of an array and declares an array of designated size: int size; int[] number; size= Integer.parseInt(JOptionPane.showInputDialog(null, "Size of an array:")); number = new int[size]; Instead of declaring the array size to a fixed value, it is possible to declare its size at the runtime. For example, we can prompt the user for the size of an array as illustrated in the sample code shown here. 11/16/2018

Arrays of Objects In Java, in addition to arrays of primitive data types, we can declare arrays of objects An array of primitive data is a powerful tool, but an array of objects is even more powerful. The use of an array of objects allows us to model the application more cleanly and logically. By combining the power of arrays and objects, we can structure programs in a clean, logical manner. Without an array of objects, to represent a collection of Account objects, for example, we need to use several different arrays, one for names, one for addresses, and so forth. This is very cumbersome and error-prone. 11/16/2018

11/16/2018 public class Person { private String name; private int age; private char gender; public Person() {age=0; name=" "; gender=' ';} public Person(String na, int ag, char gen) {setAge(ag); setName(na); setGender(gen); } public Person(Person pr) { setPerson(pr);} public void setPerson(Person p) { age=p.age; gender =p.gender; name=p.name. substring(0, p.name.length()); } public void setAge (int a) {age=a;} public void setGender (char g) {gender=g;} public void setName(String na) {name=na.substring(0, na.length());} public int getAge(){return age;} public char getGender () {return gender;} public String getName () { return name;} 11/16/2018

The Person Class We will use Person objects to illustrate the use of an array of objects. public class Person { private String name; private int age; private char gender; public Person() {age=0; name=" "; gender=' ';} public Person(String na, int ag, char gen) {setAge(ag); setName(na); setGender(gen); } public Person(Person pr) { setPerson(pr);} public void setPerson(Person p) { age=p.age; gender =p.gender; name=p.name. substring(0, p.name.length()); } public void setAge (int a) {age=a;} public void setGender (char g) {gender=g;} public void setName(String na) {name=na.substring(0, na.length());} public int getAge(){return age;} public char getGender () {return gender;} public String getName () { return name;} } 11/16/2018

Creating an Object Array - 1 Code Person[ ] person; person = new Person[20]; person[0] = new Person( ); A Only the name person is declared, no array is allocated yet. After is executed A person State of Memory 11/16/2018

Creating an Object Array - 2 Code Person[ ] person; person = new Person[20]; person[0] = new Person( ); Now the array for storing 20 Person objects is created, but the Person objects themselves are not yet created. B After is executed B 1 2 3 4 16 17 18 19 person person State of Memory 11/16/2018

Creating an Object Array - 3 Code Person[ ] person; person = new Person[20]; person[0] = new Person( ); One Person object is created and the reference to this object is placed in position 0. C 1 2 3 4 16 17 18 19 person After is executed C Person 1 2 3 4 16 17 18 19 person State of Memory 11/16/2018

Person Array Processing – Sample 2 Find the youngest and oldest persons. int minIdx = 0; //index to the youngest person int maxIdx = 0; //index to the oldest person for (int i = 1; i < person.length; i++) { if ( person[i].getAge() < person[minIdx].getAge() ) { minIdx = i; //found a younger person } else if (person[i].getAge() > person[maxIdx].getAge() ) { maxIdx = i; //found an older person } //person[minIdx] is the youngest and person[maxIdx] is the oldest Here’s another approach with two Person variables: Person youngest, //points to the youngest person oldest; //points to the oldest person youngest = oldest = person[0]; for (int i = 1; i < person.length; i++) { if ( person[i].getAge() < youngest.getAge() ) { youngest = person[i]; //found a younger person } else if ( person[i].getAge() > oldest.getAge() ) { oldest = person[i]; //found an older person outputBox.printLine("Oldest : " + oldest.getName() + " is " + oldest.getAge() + " years old."); outputBox.printLine("Youngest: " + youngest.getName() + " is " + youngest.getAge() + " years old."); 11/16/2018

Object Deletion – Approach 1 int delIdx = 1; person[delIdx] = null; Delete Person B by setting the reference in position 1 to null. A 1 2 3 person A B C D 1 2 3 person A C D Before is executed After is executed In this approach, we simply leave the position of a deleted object to a null. With this approach, an array index positions will be a mixture of null and real pointers. 11/16/2018

Object Deletion – Approach 2 int delIdx = 1, last = 3; person[delIndex] = person[last]; person[last] = null; Delete Person B by setting the reference in position 1 to the last person. A 1 2 3 person A B C D 1 2 3 person A C D Before is executed After is executed With the second approach, we divide the array into two parts: the first part contains the real references and the second part contains the null references. When we delete a node, a hole will result and we must fill this hole. There are two possible solutions. The first solution is to pack the elements. If an object at position J is removed (i.e., this position is set to null), then elements from position J+1 till the last non-null reference are shifted one position lower. And, finally, the last non-null reference is set to null. The second solution is to replace the removed element by the last element in the array. The first solution is necessary if the Person objects are arranged in some order (e.g., in ascending order of age). The second solution is a better one if the Person objects are not arranged in any order. 11/16/2018

Person Array Processing – Sample 3 Searching for a particular person. Approach 2 Deletion is used. int i = 0; while ( person[i] != null && !person[i].getName().equals("Latte") ) { i++; } if ( person[i] == null ) { //not found - unsuccessful search System.out.println("Ms. Latte was not in the array"); } else { //found - successful search System.out.println("Found Ms. Latte at position " + i); Here’s another approach with two Person variables: Person youngest, //points to the youngest person oldest; //points to the oldest person youngest = oldest = person[0]; for (int i = 1; i < person.length; i++) { if ( person[i].getAge() < youngest.getAge() ) { youngest = person[i]; //found a younger person } else if ( person[i].getAge() > oldest.getAge() ) { oldest = person[i]; //found an older person System.out.println("Oldest : " + oldest.getName() + " is " + oldest.getAge() + " years old."); System.out.println("Youngest: " + youngest.getName() + " is " + youngest.getAge() + " years old."); 11/16/2018

Passing Arrays to Methods - 1 Code A public int searchMinimum(float[] number)) { … } minOne = searchMinimum(arrayOne); At before searchMinimum A arrayOne A. Local variable number does not exist before the method execution When an array is passed to a method, only its reference is passed. A copy of the array is NOT created in the method. public int searchMinimum(float[] number) { int indexOfMinimum = 0; for (int i = 1; i < number.length; i++) { if (number[i] < number[indexOfMinimum]) { //found a indexOfMinimum = i; //smaller element } return indexOfMinimum; State of Memory 11/16/2018

Passing Arrays to Methods - 2 Code public int searchMinimum(float[] number)) { … } B minOne = searchMinimum(arrayOne); arrayOne The address is copied at B number arrayOne B. The value of the argument, which is an address, is copied to the parameter. State of Memory 11/16/2018

Passing Arrays to Methods - 3 Code public int searchMinimum(float[] number)) { … } C minOne = searchMinimum(arrayOne); arrayOne number While at inside the method C C. The array is accessed via number inside the method. State of Memory 11/16/2018

Passing Arrays to Methods - 4 Code public int searchMinimum(float[] number)) { … } minOne = searchMinimum(arrayOne); D arrayOne number arrayOne At after searchMinimum D D. The parameter is erased. The argument still points to the same object. State of Memory 11/16/2018