Arrays CSC 171 FALL 2002 LECTURE 20. Arrays Suppose we want to write a program that reads a set of test grades and prints them, marking the highest grade?

Slides:



Advertisements
Similar presentations
Arrays and ArrayLists Ananda Gunawardena. Introduction Array is a useful and powerful aggregate data structure presence in modern programming languages.
Advertisements

Chapter 13 Array Lists and Arrays. 2 ArrayList Basics Definition: An array list is a sequence of objects Construct an array List object, i.e. in the Purse.java.
Chapter 13 ARRAY LISTS AND ARRAYS. CHAPTER GOALS To become familiar with using array lists to collect objects To learn about common array algorithms To.
Chapter 13 ARRAY LISTS AND ARRAYS CHAPTER GOALS –To become familiar with using array lists to collect objects –To learn about common array algorithms –To.
Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT5: Array (1D and 2D) CS2311 Computer Programming.
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
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.
CS100A, Fall 1997, Lecture 111 CS100A, Fall 1997 Lecture 11, Tuesday, 7 October Introduction to Arrays Concepts: Array declaration and allocation Subscripting.
Chapter 7 – Arrays.
Computer Science A 10: 20/3. Array Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[] double[]
Horstmann chapter 8 continued. Sorting arrays The telephone book is easy to use, because the entries are sorted Sorting is a common task, and many many.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
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.
Datalogi A 8: 27/10. Array Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[] double[] data.
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.
Arrays CSC 171 FALL 2001 LECTURE 10. History: Alan Turing Founder of Computer Science Alan Turing developed the idea of a "Universal Machine" capable.
Chapter 8 Arrays and Strings
Chapter 9 Introduction to Arrays
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Java Unit 9: Arrays Declaring and Processing Arrays.
03/16/ What is an Array?... An array is an object that stores list of items. Each slot of an array holds an individual element. Characteristics.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.
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.
Chapter 8 Arrays and Strings
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
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.
Chapter 8: Arrays.
ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays.
Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
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.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
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.
1 Building Java Programs Chapter 3: Introduction to Parameters and Objects These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They.
Arrays An array is a data object that can hold multiple objects, all of the same type. We can think of an array as a storage box which has multiple compartments.
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.
Arrays. Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional  Java.
Arrays. Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional  Java.
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
Array Declarations Arrays contain a fixed number of variables of identical type Array declaration and allocation are separate operations Declaration examples:
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.
BIT115: Introduction to Programming
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];
Arrays and Array Lists CS 21a. Problem 1: Reversing Input Problem: Read in three numbers and then print out the numbers in reverse order Straightforward.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
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.
Chapter VII: Arrays.
Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. System.out.println(“Please enter grade.
Chapter 8 – Arrays and Array Lists
Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. cout >
Objects First with Java CITS1001
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Review of Arrays and Pointers
Data Structures (CS212D) Week # 2: Arrays.
Arrays in Java.
Arrays.
Presentation transcript:

Arrays CSC 171 FALL 2002 LECTURE 20

Arrays Suppose we want to write a program that reads a set of test grades and prints them, marking the highest grade? < - highest grade

Individual data items If we knew that there were always 150 students in the class, we could store the data as individual variables – score1,score2,score3,.., score150 What would the data entry code look like? What would the printing code look like? How about finding the max?

Arrays An array is a collection of data items of the same type Every element of the collection can be accessed separately.

___________________ is a fixed length sequence of values of the same type.

_An array__________ is a fixed length sequence of values of the same type.

Constructing Arrays double [] data = new double[10];

int x = data.length ; //instance field on arrays, x = = 10

Setting Array values To get values into an array you need to specify which slot you want to use. Specification is done with the [ ] operator The [ ] operator follows the name of the array The [ ] operator encloses and integer-valued expression called the index or subscript

Setting array values data[4] = 29.95;

Using array values Similar to setting int i = 4 ; System.out.println(“data[“+i+”] ==“+ data[i]); > data[4] ==29.95

You access array elements with and integer position number, called the _______________, using the notation _______________.

You access array elements with and integer position number, called the ___index_______, using the notation ____a[index]___________.

Array data items Suppose we want to write a program that reads a set of test grades and prints them, marking the highest grade? What would the data entry code look like? What would the printing code look like? How about finding the max?

Array issues Does it work? double [] data = new double[10]; data[10] = 5.4;

Array issues Does it work? double [] data = new double[10]; data[10] = 5.4; When the program runs, an out-of-bounds subscript generates an exception and terminates the program – why?

Position numbers of an array range from _________ to ____________.

Position numbers of an array range from ___0_______ to ____a.length -1_________.

Accessing a nonexistent position results is a ______________ error.

Accessing a nonexistent position results is a _bounds_____ error.

Use the ___________________field to find the number of elements in an array.

Use the _____length______field to find the number of elements in an array.

Array issues Can we search for the top grade as follows double maxScore = data[0]; for (int i = 1;I<=data.length;i++) If (data[i] > maxScore) maxScore = data[i];

Array issues An array of length n has index values from 0 to (n-1) double maxScore = data[0]; for (int i = 1;I<data.length;i++) If (data[i] > maxScore) maxScore = data[i];

Array issues Does it work? public static void main(String[] args){ double[] data; If (data[0] > 4.0) System.out.println(“GT 4!”); }

Array issues Arrays must be allocated! public static void main(String[] args){ double[] data = new double[10]; If (data[0] > 4.0) System.out.println(“GT 4!”); }

Array issues Arrays can be initialized! public static void main(String[] args){ double[] data = {2,3,4,5,6}; If (data[0] > 4.0) System.out.println(“GT 4!”); } // note: new int[] {2,3,4,5,6} ; is also legal

Copying Arrays Is this ok? double [] data = new double[10]; double[] testScores; testScores = data;

Copying Arrays Is this ok? double [] data = new double[10]; double[] testScores; testScores = data; How many arrays are there?

Copying Array REFERENCES double [] data = new double[10]; double[] testScores; testScores = data;

Copying Arrays So, what if we want to make two “real” copies – what does the code look like? Write a method so that int[] x = {3,4,5,6,7,8,9,10}; int[] y = myCopy(x);

Copying public static int[] myCopy(int[] x){ int[] r_arry = new int[x.length]; for (int i = 0 ; i< x.length;i++) r_arry[i] = x[i]; return r_arry; }

System.arrayCopy //System.arraycopy(from,fromstart,to,toStart,count); System.arraycopy(data,0,prices,0,data.length);

Clone

An array variable stores a ________________________. Copying the variable yields a second ____________________ to _________________ array.

An array variable stores a ______reference__________. Copying the variable yields a second ______reference______________ to ____the same_____________ array.

Use the ________________ method to copy the elements of an array.

Use the ____clone______ method to copy the elements of an array.

Use the _____________________________ method to copy elements from one array to another.

Use the _System.arraycopy____________________ method to copy elements from one array to another.

If you run out of space in an array you need to _______________ a larger array and copy the elements into it.

If you run out of space in an array you need to __allocate_____ a larger array and copy the elements into it.

Getting a Bigger Array

More Arrays Suppose we want to write a program that reads a set of test product names, prices, and quality scores prints them, marking the best value? (score/prices) Digital 500X, $ , score 73 ZEOS Pentium-III/500, $ , score 70 Micro Express MF, $ , score 72 < - best value Polywell Poly 450IP, $ , score 30

Parallel Arrays One solution, can you think of a better one?

Arrays of Objects Easier to deal with - arrays hold references

Avoid ___________________________ arrays by changing them into arrays of objects.

Avoid ____________parallel_______ arrays by changing them into arrays of objects.

Multidimensional Arrays Arrays of arrays – Arrays are objects – Arrays hold references to objects – Ergo, arrays can hold arrays

Tables are 2D arrays int size = 5; int[][] mtable = new int[size][size]; for(i=0;i<size;i++) for(int j=0;j<size;j++) mtable[i][j] = (i+1)*(j+1); // how easy to modify code ???? int[][] mtable = new int[5][5]; for(i=0;i<5;i++) for(int j=0;j<5;j++) mtable[i][j] = (i+1)*(j+1);

Arrays of Arrays int [][] powers = new int[10][10];

Arrays of Arrays int [][] pow2 = {{1,2,3},{4,5,6},{7,8,9}};

Allocating arrays of arrays int size = 10; int[][] mtable = new int[size][]; for(i=0;i<mtable.length;i++) { mtable[i]= new int[size]; for(int j=0;j<mtable[i].length;j++) mtable[i][j] = (i+1)*(j+1); }

Alternately The following is legal. What is the structure? int[][] b = new int[5][]; for (int i=0;i<b.length;i++) b[i] = new int[i+1];

Alternately int[][] b = new int[5][]; for (int i=0;i<b.length;i++) b[i] = new int[i+1]; This is known as a triangular array Is b[3][1] a legal reference or b[1][3]?

Two dimensional arrays form a ___________________________ arrangement. You access elements with an index pair using the notation ______________.

Two dimensional arrays form a _tabular, two dimensional_______ arrangement. You access elements with an index pair using the notation _____a[i][j]_________.

Passing Arrays In JAVA – Primitives are passed by value A copy of the variable is made & used Modifications made do not affect calling value public void myAdd(int x) { x++;} – Objects are passed by reference Since the reference is passed it is possible to change the value in the calling method Public void myAdd (int[] x) {x[0]++;}

Pass by value public class passArry { public static void main(String args[]){ int x1 = 3; System.out.println("x1 == "+x1); myAdd(x1); System.out.println("x1 == "+x1); } public static void myAdd(int x) {x++;} }

Pass by reference public class passArry { public static void main(String args[]){ int[] x2 = {4,5,6}; System.out.println("x2[0] == "+x2[0]); myAdd(x2); System.out.println("x2[0] == "+x2[0]); } public static void myAdd(int[] x) {x[0]++;} }

Local reference class Student { int age; // ….. public void setAge(int age){ age = age; } }

Local reference class Student { int age; // ….. public void setAge(int age){ this.age = age; }

Exercise Write a method that takes an integer array and prints the values

Exercise public static int myPrint(int[] x){ for (int i = 0 ; i<x.length;i++) System.out.println(x + “[“+i+”] == “+ x[i]); }

Exercise Write a method that takes an integer array, and two integer indices and swaps the value

Exercise public static void mySwap(int[] x, int i, int j){ int temp = x[i]; x[i] = x[j]; x[j] = temp; }

Interpretive Dance Some people are “visual” learners Some people are “aural” learners Some people are “symbolic” learners Some people are “body” learners Every kindergardener learns how to sort.

Sorting Write a method that takes an array and sorts via the kindergarden method.

Bubblesort public static void bubbleSort(int[] x){ for (int j=0;j<x.length;j++) for (int i = 0 ; i<x.length-1;i++) if (x[i] > x[i+1]) mySwap(x,i,i+1); } // how many comparisions do we make?

Counting comparisons If the length of the array is “n” The outer loop executes “n” time Each time the outer loop executes, the inner loop executes “(n-1)” time So, we get n(n-1) comparisions

Exercise: SEARCH Write a method that takes an integer array and returns the index of the maximum value

Exercise public static int myMax(int[] x){ int rvalue = 0; for (int i = 0 ; i<x.length;i++) if (x[i] > x[rvalue]) rvalue = i; return rvalue; }

Exercise Overload the max finder to take an array and an index – the method now returns the index of the maximum value >= the index passed in

Exercise public static int myMax(int[] x, int j){ int rvalue = j; for (int i = j ; i<x.length;i++) if (x[i] > x[rvalue]) rvalue = i; return rvalue; }

Sorting Write a method that takes an integer array Loop through all the positions in the array, one after the other At each (current) position, find the max from that position to the rest of the array. Swap the value with the current position This is termed selection sort

Selection Sort Does it work? public void selSort(int x){ for (int i = 0 ; i<x.length;i++){ int temp = myMax(x,i); mySwap(x,i,temp); } Can you prove it works? What is the loop invariant?

Swap max “^” with first “|” {1,9,2,8,3,7,4,6,5} | ^ {9,1,2,8,3,7,4,6,5} | ^ {9,8,2,1,3,7,4,6,5} | ^ {9,8,7,1,3,2,4,6,5} | ^ {9,8,7,6,3,2,4,1,5} | ^ {9,8,7,6,5,2,4,1,3} | ^ {9,8,7,6,5,4,2,1,3} | ^ {9,8,7,6,5,4,3,1,2} | ^

Run time analysis How long does it take SectionSort to run on an array of a given length?

Count the loops n is the length of the array The outer (i) loop executes from 0 to n-2 – n-1 times The on each cycle of the outer loop i has a certain (different) value On each cycle of the outer loop, the inner loop executes from I + 1 to n –1 – n – i – 1 times

So, we get N-2  n-i-1) i=0

Can we prove ? N-2  n-i-1) = = i=0  n(n-1)/2

Array Lists Consider Purse class Purse doesn't remember individual Coin objects, just the total Don't know how many coins--can't have variables coin1...coin10 Use ArrayList to store variable number of objects ArrayList coins = new ArrayList(); coins.add(new Coin(0.1, "dime"));... size method yields number of elements

An ______________________ is a sequence of objects.

An _array list______ is a sequence of objects.

Retrieving Array List Elements Use get method Index starts at 0 Must cast to correct type Coin c = coins.get(0); // gets first coin Bounds error if index is out of range Most common bounds error: int n = coins.size(); c = (Coin)coins.get(n); // ERROR // legal index values are 0...n-1

To store a primitive type in an array list you must use a ____________ class.

To store a primitive type in an array list you must use a __wrapper__ class.

When retrieving an element from an array list, you need to ________________ the return value of the ________________ method to the element class.

When retrieving an element from an array list, you need to __cast____ the return value of the _______get__ method to the element class.

Position number of an array list range from _________ to _______________. Accessing a nonexistent position results in a _________ error.

Position number of an array list range from _____0____ to ________size() - 1_______. Accessing a nonexistent position results in a ___counds______ error.