Chapter 5 Arrays and Vectors An array allows you to group data items together in a structure that is processed via an index. They allow you to process.

Slides:



Advertisements
Similar presentations
Introduction to arrays
Advertisements

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.
For use of IST410 Students only Arrays-1 Arrays. For use of IST410 Students only Arrays-2 Objectives l Declaring arrays l Instantiating arrays l Using.
Chapter 7 – Arrays.
Arrays Chapter 6 Chapter 6.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
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.
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.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Chapter 7: Working with 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.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - JavaScript: Arrays Outline 11.1 Introduction 11.2 Arrays 11.3 Declaring and Allocating Arrays.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
Arrays Chapter 7. 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores : Inspecting.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
ARRAYS 1 Week 2. Data Structures  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently 
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.
© 2007 Lawrenceville Press Slide 1 Chapter 10 Arrays  Can store many of the same kind of data together  Allows a collection of related values to be stored.
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.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
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.
Computer Programming 12 Mr. Jean April 24, The plan: Video clip of the day Upcoming Quiz Sample arrays Using arrays More about arrays.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
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.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
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,
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
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.
CS 180 Recitation 7 Arrays. Used to store similar values or objects. An array is an indexed collection of data values of the same type. Arrays are the.
Two Dimensional Arrays Found in chapter 8, Section 8.9.
Arrays Chapter 7. 2 Declaring and Creating Arrays Recall that an array is a collection of elements all of the _____________ Array objects in Java must.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Arrays Chapter 7.
Arrays Chapter 7.
Chapter-7 part3 Arrays Two-Dimensional Arrays The ArrayList Class.
Arrays … The Sequel Applications and Extensions
Can store many of the same kind of data together
Chapter 8 Slides from GaddisText
Can store many of the same kind of data together
Object Oriented Programming in java
Arrays Chapter 7.
Can store many of the same kind of data together
Arrays.
Presentation transcript:

Chapter 5 Arrays and Vectors An array allows you to group data items together in a structure that is processed via an index. They allow you to process like data items as a group. Objects can also be stored in an array.

Array declarations and indices An array is a data structure in which we store a collection of data items of the same type. Arrays have a single variable name associated with the entire collection. Array of scores: scores

Arrays Arrays are stored in consecutive memory locations in main memory. We can pass entire arrays to methods We can access the individual array elements. We can process the individual elements like other simple variables.

Declaring arrays Double[] salary = new double[50]; Declares an array of type double that can hold 50 values Array type Array name Array size

Declaring arrays int[] coinValues = {1, 5, 10, 25, 50}; Alternative method to declare and initialize array. What is the length of the array? Array Type Array name Array Values

Syntax Display Form: elementType[] arrayName = new elementType[size]; elementType[] arrayName = {list-of-values}; arrayName represents a collection of array elements each element can store an item of type elementType The size maybe specified or calculated based on the number of values in the list-of-values. These items are stored sequentially. elementType can be primitive type or class

Declaration versus Storage allocation You can declare an array and storage separately. double[] salary; salary = new double[50]; Why would you want to do this?

Processing array elements An array index is used to process the individual array elements. You use the array name and an index displayResult(salary[1]); You can use this anywhere you would use a value of that type. The index is either an integer or an integer expression.

Indexed variable When access array elements you start at index 0 rather than 1. salary[1] is called an indexed variable. Salary is type double so we can use this anywhere we use a double, arithmetic operators, relational operators, the assignment operator……..

Examples Review example 5.1 on page This uses literals as index Review example 5.2 on page 276 This uses variables as the index You must be assured that the variable is in the valid range of index values. Out of bounds error Occurs at runtime

Section 5.2 processing arrays For loops are typically used to process an array They allow you to process all elements in an array in some way Can be used to: Enter data Display contents Perform other processing

Data field length Java automatically allocates a data field Length Allocated for each array Stores the array size in this data field Can be used to process an array. See code example 5.3 page 279

Example code int[] example = new int[5]; for (int i = 0; i < example.length; i++) example[i] = getInt("please enter an integer"); for (int i = 4; i >= 0; i--) displayResult(example[i]); }

See code page Calculates the cubes of numbers 1-10

Array cube example First create array but does not set length private int[] cubes; Then sets length of array via cubes = new int[numCubes];

Array cube example Fills the array via: for (int i = 0; i < cubes.length; i++) cubes[i] = i * i * i; Calculates the sum of cubes: for (int i = 0; i < cubes.length; i++) sumCubes += cubes[i];

Array cube example Displays results via for (int i = 0; i < cubes.length; i++) “glues” string together next Look at running of example code.

Case Study Pages Problem Analysis Design Implementation

Operations on whole arrays 5.3 Can pass an entire array as an argument Assign values from on array to another Copy data from one array to another

Array copy System.arraycopy(sourceArray, sourcePosition, destinationArray, destinationPostion, count); System.arraycopy(y, 0, x, 0, y.length); Copies y to x but remain separate arrays System.arraycopy(y, 0, x, 2, 3); Copies y starting at 0 for next 3 positions to x starting at position 2

Given that you have 2 arrays private int[] x = new int[5]; private int[] y = new int[5];

Array Assignment x = y; Makes x and y occupy the same storage space! Very different than other assignment statements. They are now identical If you change elements of one it changes the other. (same storage space)

Why?? When you declare an array int[] x = new int[5]; This allocates 5 storage locations x[0] through x[4]; Additionally java allocates an additional storage location x which contains the address of the start of the array

Why? x X[0] X[1] X[3]X[2]X[4]

Why? x X[0] X[1] X[3]X[2]X[4] y = x; yOld array y

Example 5.16 Page Accepts in 2 arrays Returns true is they are equal Middle of page Calls the method

Example 5.7 page Adds 2 arrays Accepts in 2 integer arrays Returns an array which is the sum of the respective elements in the arrays sent

Section 5.4 Searching and Sorting an Array Two common things that are done with an array are: Searching Sorting When we search an array you compare each value to a target, which is the value you are seeking

PseudoCode For each array element If the current element contains the target return the index of the current element If none found return -1

Implementation To test each element of the array we would use a for loop. The arrays length attribute can be used for the upper limit (< length)

Search code public static int search(int[] x, int target) { for (int i = 0; i < x.length; i++) if (x[i] == target) return i; //index of target // All elements tested without success. return -1; }

Sorting array Selection sort is a simple sorting algorithm It is not a very efficient algorithm Finds smallest element in the array and switches it with element in position 0 Finds next smallest element and switches it with position 1 And so on…..

Pseudocode For each index, fill, in the array up to but excluding, the last index Find the smallest element in the subarray starting at scores[fill] If the smallest element is not at index fill Exchange the smallest element with the one at index fill See code trace page 300

Switching values If you want to change to values x, y need a third storage location temp = x; x = y; y = temp;

Sort program Look at sorting code on page 301 Method selectSort Method findPosMin Look at selection sort running at or/Animator.html or/Animator.html

Median Value Easy to find median in sorted Array Simply one in the middle public static int findMedian(int x[]) { // Create a copy of array x. int[] copyX = new int[x.length]; System.arraycopy(x, 0, copyX, 0, x.length); selectSort(copyX); // Sort array copyX if (x.length % 2 == 1) return copyX[x.length / 2]; else return (copyX[(x.length / 2) – 1] + copyX[x.length/2]) / 2; }

Arrays of Objects 7.5 Arrays can be declared of any type in Java. When you create an array of objects you actually have an array of null references to objects. Employee[] employees new Employee[5] Allocates storage for 5 references to an employee object, you must initialize it.

Examples Page Example shows creating an array of references to 5 strings. Page 304 shows creating array and then setting values. Page 305 this declares the array and initializes it at the same time.

Array of string as argument You can pass array of strings to methods. We have been using the format all along. public static void main(String[] args); Passes command line parameters into the program as string arguments

Code looks like this public static void main(String[] args) { if (args.length > 0) for(int i = args.length - 1; i >=0; i--) System.out.println(args[i]); else System.out.println("No command line args - no fun!"); }

Case study Payroll problem Uses company class to include array of employee objects from section 4.4 New company needs to include 2 new data items Array of employees Total Gross pay

Case study Payroll problem pages Implementation Notice readPayrollData, simply uses a for loop to instantiate the objects and call method to prompt user for data. computePayRoll uses a for loop to total the pay of all employees Could this, Should this have been a part of readAllEmpData??

Case study Payroll problem Implementation I have a problem with the design of this. It revolves around the data field payroll And the method computePayroll Especially being public Any ideas what I don’t like about this?

Case Study Phone Directory Study the Phone Directory Case study Work to understand this! Come with questions for next time.

Multidimensional Arrays section 5.6 How many can we have? Two dimensional are the most common arrays. These allow more complex structures than just the linear nature of single dimensional arrays.

Multidimensional Arrays The rules for element types of multidimensional arrays are the same for single dimensional arrays Must be the same type Can be simple or objects Most commonly used to represent a table of elements

Declaring 2 dimensional arrays char [] [] ticTacToe = new char[3][3]; This is a 2d array with 3 rows and 3 columns. ticTacToe [1] [2] Array name Row index Column index

Initializing a two-dimensional array double [] [] matrix = {{5.0, 4.5, 3.0}, {-16.0, -5.9, 0.0}}; Creates an 2 X 3 array Col 0Col 1Col 2 Row Row

Nested loops for processing 2d arrays. You need to decide what order you intend on accessing the array. If in row order, then the row index in used in the outer loop. If in column order then the column index is in the outer loop.

Nested loops for processing 2d arrays. Pseudocode: for each row r in the array for each column c in the array process the element with indices [r] [c]

Code to process int intArray [] [] = new int [3] [3]; for (int row = 0; row < intArray.length, row++) for (int col = 0; col < intArray[row].length, col++) process each array element intArray[row] [col]

Arrays with different row lengths Since each row of a 2d array is it’s own 1d array the length of all row need not be equal

Arrays > 2d Why? Each row is a player and each column is how many hits they had in each game. 2d array represents a team with each column a different player 3d represents all the teams in the league 4d represents various seasons for the league

Section 7.7 Vectors Vectors are a class within java. They allow for much of the flexibility that you will learn to implement in CS2 Must import java.util.*; Only works with objects not primitive types

Vector attributes Allows structure to grow and shrink as needed Allows you to: Add elements Retrieve elements Insert elements Remove elements

Example 5.14 Page 329 Uses vector to store a collection of employees Vector employees = new Vector(); employees.addElement(employeeA); employees.addElement(employeeB); Puts employeeA at index 0 Puts employeeB at index 1

Accessing elements anEmployee = (Employee)employees.elementAt(1); Assigns to an Employee the second element in array elementAt returns a type object so you must type cast it to the appropriate type (Employee)

Other methods setElementAt Allows you to change an element in the vector insertElementAt Allows you to insert an element anywhere in the vector removeElementAt Allows you to delete any element in the vector See table 5.3 page 332

Review re-do of phone book On pages 334 – 336 is a re-do of the Phone Book app you looked at before. Study and compare this to the previous example and come prepare to ask any questions next time

Wrapper classes Section 5.8 Vectors can only work on objects not primitive data types A Wrapper class encapsulates a primitive type and allows it to function as an object. Contains methods for converting back and forth.

Wrapper class methods Constructor takes primitive type and create object of that type class new Double( ) Holds real number in type Double object

Wrapper class methods Constructor to decode string into objects initial value Double w = new Double(“ ”); Stores in object of type Double that is called w

Wrapper class methods toString method creates string version w.toString() creates “ ” typeValue gives primitive type value w.DoubleValue() gives equals compares objects of same type x.equals(y) is true if the wrap the same value

Vectors and Wrappers You need to know what vectors are Characteristics Capabilities Uses You need to know what Wrapper classes are Capabilities Uses

Section 5.9 Arrays and ArrayList collection classes Arrays class provides a set of static methods to process arrays fill() sort() binarySearch() equals() We will write our own for some of these

ArrayList Provides and indexed collection behave like a vector has greater performance See methods page 343 See Phone book re-write using ArrayList Pages

Common programming errors Most common error is index going outside the bounds of the array May want to display index to be sure that it is processing properly. Index type must be integer Must declare array and create an instance or it. If not get null pointer error

Common programming errors Vectors Do not remove more data than is in the vector Be sure to type cast objects as you remove them To store primitives in vector must use wrapper class