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

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.
Arrays.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 2D Arrays.
©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.
Introduction to arrays. Array Homogeneous collection of components stored in adjacent memory locations –All elements share same data type –Entire collection.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
بسم الله الرحمن الرحيم 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 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 *Arrays with more than one dimension *Java Collections API.
©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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Arrays Lists.
Chapter 7 Arrays C++ Programming, Namiq Sultan1 Namiq Sultan University of Duhok Department of Electrical and Computer Engineering Reference: Starting.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 10 Arrays and Collections.
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Chapter 9 Introduction to Arrays
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Repetition Statements.
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,
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
Chapter 10 2D Arrays Collection Classes. Topics Arrays with more than one dimension Java Collections API ArrayList Map.
Chapter 17 Pointers and Arrays. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Pointers and Arrays.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
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.
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.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
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.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Array Basics An array is a collection of data.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Most of these slides are based on “Intro to.
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.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,
Arrays Adapted from materials created by Dr. Donald Bell, Cal Poly 2000 (updated February 2004)
CS1101: Programming Methodology Recitation 5 – Arrays and Collections.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Two Dimensional Arrays Found in chapter 8, Section 8.9.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Files Most of these slides.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Arrays (adapted from the publisher’s.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays Collections of data Winter 2004CS-1010 Dr. Mark L. Hornick 1.
1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Most of these slides are.
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 10 Arrays Animated Version
Chapter 8 - Arrays.
Chapter 7 Part 1 Edited by JJ Shepherd
Basic Files + (Chapter 10 – Arrays) : Objectives
Chapter 6: Arrays.
Chapter 10 Arrays ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Chapter 6: Arrays.
Object Oriented Programming in java
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,
Presentation transcript:

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

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Array Basics Suppose we have a sequence of data values which all need to be processed in the same way. –We would like to use a loop but how do we process a different variable each time through the loop? An array is an indexed collection of data values. If your program needs to deal with 100 integers, 500 Account objects, 365 real numbers, etc., you can use an array. An array is a collection of data values of the same type.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Arrays of Primitive Data Types Array variables are reference types (like objects) Array Declaration [ ] //variation 1 [ ]//variation 2 Array Instantiation (Creation) = new [ ] Example double[ ] rainfall; rainfall = new double[12]; Variation 1 double rainfall [ ]; rainfall = new double[12]; Variation 2 An array is like an object!

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Accessing Individual Elements Each array has a variable named length associated with it. Individual elements in an array accessed by index. double[] rainfall = new double[12]; The index of the first position in an array is 0. rainfall rainfall[2] This indexed expression refers to the element at position #2 rainfall.length is 12

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Reading Data into an Array double[] rainfall = new double[12]; double annualAverage, sum = 0.0; Scanner kbd = new Scanner( System.in); for (int i = 0; i < rainfall.length; i++) { System.out.println("Rainfall for month " + (i+1)); rainfall[i] = kbd.nextDouble(); sum += rainfall[i]; } annualAverage = sum / rainfall.length; The public constant length returns the capacity of an array.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Using an Array of Strings double[] rainfall = new double[12]; String[] monthName = new String[12]; monthName[0] = "January"; monthName[1] = "February"; … double annualAverage, sum = 0.0; Scanner kbd = new Scanner( System.in); for (int i = 0; i < rainfall.length; i++) { System.out.println("Rainfall for month " + monthName[i]); rainfall[i] = kbd.nextDouble(); sum += rainfall[i]; } annualAverage = sum / rainfall.length; The same pattern for the remaining ten months. The actual month name instead of a number.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Use Loops to Process Array Data 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 }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 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, , 18.2, 9.00, 3.123, , }; String[] monthName = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; number.length samplingData.length monthName.length

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Array Size Specification The size of an array can be specified as a constant or an expression The following code prompts the user for the size of an array and declares an array of designated size: int size; Scanner kbd = new Scanner( System.in); int[] number; System.out.println("Size of an array:"); size= kbd.nextInt(); number = new int[size];

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Arrays of Objects 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.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter The Person Class We will use Person objects to illustrate the use of an array of objects. Person latte; latte = new Person( ); latte.setName("Ms. Latte"); latte.setAge(20); latte.setGender('F'); System.out.println( "Name: " + latte.getName() ); System.out.println( "Age : " + latte.getAge() ); System.out.println( "Sex : " + latte.getGender() ); The Person class supports the set methods and get methods.c

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Creating an Object Array - 1 Code State of Memory Person[ ] person; person = new Person[20]; person[0] = new Person( ); A A Only the name person is declared, no array is allocated yet.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter person Creating an Object Array - 2 Code State of Memory Person[ ] person; person = new Person[20]; person[0] = new Person( ); B B Now the array for storing 20 Person objects is created, but the Person objects themselves are not yet created. After is executed B person

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Creating an Object Array - 3 Code State of Memory Person[ ] person; person = new Person[20]; person[0] = new Person( ); C C One Person object is created and the reference to this object is placed in position person person After is executed C Person

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Person Array Processing – Sample 1 Create Person objects and set up the person array. String name, inpStr; intage; chargender; Scanner kbd = new Scanner( System.in); for (int i = 0; i < person.length; i++) { //read in data values System.out.println("Enter name:" ); name = kbd.next(); System.out.println("Enter age:" ); age= kbd.nextInt(); System.out.println("Enter gender:" ); inpStr= kbd.next(); gender = inpStr.charAt(0); //create a new Person and assign values person[i] = new Person( name, age, gender); }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Person Array Processing – Sample 2 Find the youngest and oldest persons. intminIdx = 0;//index to the youngest person intmaxIdx = 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

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Partially Filled Arrays We don't always know how big an array we need –What happens if we aren't using all the elements? Fill the array in order and use a counter variable to keep track of how many elements have been used –Don't leave holes For object arrays, can use the first null element as a sentinal –What happens if we run out of room? Allocate a new block of memory (using new) Copy all the elements from the old array to the new one Set the reference to the new array

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Object Deletion – Approach 1 int delIdx = 1; person[delIdx] = null; Delete Person B by setting the reference in position 1 to null person A B C D A A 0123 AC D Before is executed A After is executed A

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 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 person A B C D A A 0123 AC D Before is executed A After is executed A

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Person Array Processing – Sample 3 Searching for a particular person. 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); }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Passing Arrays to Methods - 1 Code State of Memory minOne = searchMinimum(arrayOne); public int searchMinimum(float[] number)) { … } A A At before searchMinimum A arrayOne A. A. Local variable number does not exist before the method execution

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Passing Arrays to Methods - 2 Code State of Memory minOne = searchMinimum(arrayOne); public int searchMinimum(float[] number)) { … } arrayOne B B The address is copied at B number B. B. The value of the argument, which is an address, is copied to the parameter.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter arrayOne number While at inside the method C C Passing Arrays to Methods - 3 Code State of Memory minOne = searchMinimum(arrayOne); public int searchMinimum(float[] number)) { … } C C C. C. The array is accessed via number inside the method.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter arrayOne number Passing Arrays to Methods - 4 Code State of Memory minOne = searchMinimum(arrayOne); public int searchMinimum(float[] number)) { … } D arrayOne At after searchMinimum D D. D. The parameter is erased. The argument still points to the same object.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Arrays are objects What do you think will happen if you do the following? System.out.println( array); –To print the individual elements, you need to use a loop. What do you expect the comparison a==b to do? –To compare the individual elements of a and b you need to write a loop.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Arrays Class The Arrays class has a number of useful static methods –equals does an element by element comparison of two arrays uses equals to compare objects –toString returns a string representation of the array –binarySearch and sort methods will be discussed in Chapter 11 Arrays is in the java.util package

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Array Practice Consider the array declared below double [] number = new double[25] a)What is number.length ? b)Show how to set the last element to c)Write code to compute the sum of all the negative numbers stored in the array.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter for Loops with Arrays We can use a for loop to process all the elements of an array. for (int i=0; i<array.length; i++) { /* process array[i] /* } Java 1.5 added a new loop syntax to be used with arrays and collections for (element : array) { /* process element /* } This loop iterates through all the elements in the array but you don't need to use an index

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Two-Dimensional Arrays Two-dimensional arrays are useful in representing tabular information.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Declaring and Creating a 2-D Array Declaration [][] //variation 1 [][] //variation 2 Creation = new [ ][ ] Example double[][] payScaleTable; payScaleTable = new double[4][5]; payScaleTable

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Accessing an Element An element in a two-dimensional array is accessed by its row and column index.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Sample 2-D Array Processing Find the average of each row. double[ ] average = { 0.0, 0.0, 0.0, 0.0 }; for (int i = 0; i < payScaleTable.length; i++) { for (int j = 0; j < payScaleTable[i].length; j++) { average[i] += payScaleTable[i][j]; } average[i] = average[i] / payScaleTable[i].length; }

Java Implementation of 2-D Arrays The sample array creation payScaleTable = new double[4][5]; is really a shorthand for payScaleTable = new double [4][ ]; payScaleTable[0] = new double [5]; payScaleTable[1] = new double [5]; payScaleTable[2] = new double [5]; payScaleTable[3] = new double [5];

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Ragged Arrays Subarrays may be different lengths. Executing triangularArray = new double[4][ ]; for (int i = 0; i < 4; i++) triangularArray[i] = new double [i + 1]; results in an array that looks like:

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Array Practice Trace the following code fragments for the array declared int [] array = {1, 2, 3, 5, 8, 13} 1) for (int i=0; i<array.length; i++) if (i %2==0) System.out.println( array[i]); 2) for (int i=0; i<array.length; i++) if (array[I] %2==0) System.out.println( array[i]);