Unit 5 1 Arrays and Vectors H Arrays and vectors are objects that help us organize large amounts of information H We will talk about: array declaration.

Slides:



Advertisements
Similar presentations
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.
Advertisements

CSCI 1100/ , 6.2, 6.4 April 12, 15, 17.
Lecture 6 b Last time: array declaration and instantiationarray declaration and instantiation array referencearray reference bounds checkingbounds checking.
Arrays.
1 (c) elsaddik CSI 1102 Introduction to Software Design Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
ECE122 L14: Two Dimensional Arrays March 27, 2007 ECE 122 Engineering Problem Solving with Java Lecture 14 Two Dimensional Arrays.
Arrays Clark Savage Turner, J.D., Ph.D. Copyright © 2000 by C Scheftic. All rights reserved. These notes do rely heavily.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 More on Arrays Passing arrays to or from methods Arrays of objects Command line arguments Variable length parameter lists Two dimensional arrays Reading.
1 One-Dimensional (1-D) Array Overview l Why do we need 1-D array l 1-D array declaration and Initialization l Accessing elements of a 1-D array l Passing.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
1 Modelling 1-D Array Overview l Why do we need 1-D array l 1-D array declaration and Initialization l Accessing elements of a 1-D array l Passing Array.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and 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.
Slide 1 of 57. Lecture F - Arrays Unit F1 - Introduction to Arrays.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Java Types float, double long, int, short byte char boolean Objects Objects are created by : Declaring a reference and calling a constructor. Basic types.
Class design. int month; int year class Month Defining Classes A class contains data declarations (state) and method declarations (behaviors) Data declarations.
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
Chapter 6: Arrays Java Software Solutions Third Edition
Java Unit 9: Arrays Declaring and Processing Arrays.
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
Text Book: M. T. Goodrich and R. Tamassia, "Data Structures and Algorithms in Java," 4th edition, 2006, Wiley & Sons, Inc., ISBN Text Book:
7. Arrays. Topics Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 Dr. Seuss again: "Too Many Daves"  Did I ever tell you that Mrs. McCave Had twenty-three sons, and she named them all Dave?  Well, she did. And that.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 6: Arrays Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
CSE 501N Fall ‘09 08: Arrays 22 September 2009 Nicholas Leidenfrost.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 7 Arrays 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Programming in Java (COP 2250) Lecture Chengyong Yang Fall, 2005.
Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Chapter 7: Arrays.
Chapter overview This chapter focuses on Array declaration and use Bounds checking and capacity Arrays storing object references Variable length parameter.
Chapter 7 Arrays: Part 1 of 2. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
© 2004 Pearson Addison-Wesley. All rights reserved October 15, 2007 Searching ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
1 Lecture 6 Objects for Organizing Data Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Chapter 7 Arrays 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
1 Objects for Organizing Data -- Introduction zAs our programs get more sophisticated, we need assistance organizing large amounts of data zChapter 6 focuses.
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];
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.
COS 312 DAY 12 Tony Gauvin. Ch 1 -2 Agenda Questions? First Progress report due Assignment corrected 1 MIA – 2 A’s, 2 B’s, 1 D, 1 F and 1 MIA – Code\pig.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
© 2004 Pearson Addison-Wesley. All rights reserved7-1 Array review Array of primitives int [] count; count = new int[10]; Array of objects Grade [] cs239;
Arrays. Arrays are objects that help us organize large amounts of information.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 The if-else Statement An else clause can be added to an if statement to make an if-else statement.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
Lecture 5 array declaration and instantiation array reference
Arrays of Objects October 9, 2006 ComS 207: Programming I (in Java)
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
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.
Arrays in Java.
Visual Programming COMP-315
Arrays of Objects October 8, 2007 ComS 207: Programming I (in Java)
Arrays.
Presentation transcript:

unit 5 1 Arrays and Vectors H Arrays and vectors are objects that help us organize large amounts of information H We will talk about: array declaration and use arrays of objects multidimensional arrays the Vector class basic programming concepts object oriented programming topics in computer science syllabus

unit 5 2 Arrays H An array is an ordered list of values An array of size N is indexed from zero to N-1 scores The entire array has a single name Each value has a numeric index This array holds 10 values that are indexed from 0 to 9

unit 5 3 Refering to Array Elements H A particular value in an array is referenced using the array name followed by the index in brackets  For example, the expression scores[2] refers to the value 94 (the 3rd value in the array)  scores[2] represents a place to store a single integer, and can be used wherever an integer variable can H For example, it can be assigned a value, printed, or used in a calculation

unit 5 4 Array Type H An array stores multiple values of the same type, primitive types or objects. Examples: an array of integers, an array of characters, an array of String objects H In Java, the array itself is an object. Therefore the name of the array is a object reference variable, and the array itself is instantiated separately

unit 5 5 Array Declaration  The scores array could be declared as follows: int[] scores = new int[10]; Note that the type of the array does not specify its size, but each object of that type has a specific size  The type of the variable scores is int[] (an array of integers) H It is set to a new array object that can hold 10 integers

unit 5 6 public class BasicArray { final static int LIMIT = 15; final static int MULTIPLE = 10; // // Creates an array, fills it with integer values, // modifies one value, then prints them out. // public static void main (String[] args) { int[] list = new int[LIMIT]; list זכרון

unit 5 7 public class BasicArray { final static int LIMIT = 15; final static int MULTIPLE = 10; // // Creates aan rray, fills it with integer values, // modifies one value, then prints them out. // public static void main (String[] args) { int[] list = new int[LIMIT]; // Initialize the array values for (int index = 0; index < LIMIT; index++) list[index] = index * MULTIPLE; list זכרון

unit 5 8 public class BasicArray { final static int LIMIT = 15; final static int MULTIPLE = 10; // // Creates aan rray, fills it with integer values, // modifies one value, then prints them out. // public static void main (String[] args) { int[] list = new int[LIMIT]; // Initialize the array values for (int index = 0; index < LIMIT; index++) list[index] = index * MULTIPLE; for (int index = 0; index < LIMIT; index++) System.out.print (list[index] + " "); System.out.println (); } } list[4] = 99; // change one array value 99 list זכרון מסך

unit 5 9 Examples of array declarations: float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750];

unit 5 10 Bounds Checking H Once an array is created, it has a fixed size H An index used in an array reference must specify a valid element: value must be within bounds (0 to N-1) H The Java interpreter will detect an error if an array index is out of bounds; this is called automatic bounds checking

unit 5 11 Bounds Checking  For example, if the array codes can hold 100 values, it can only be indexed using the numbers 0 to 99  If count has the value 100, the Jave interpretter will give the message “ Array Out Of Bounds ” H It’s common to introduce off-by-one errors when using arrays: int[] codes = new int[100]; for (int index=1; index <= 100; index++) codes[index] = index*50 + epsilon; problem

unit 5 12 Number of array elements  Each array object has a public constant called length that stores the size of the array H It is referenced using the array name (just like any other object): scores.length  Note that length holds the number of elements, not the largest index

unit 5 13 // ReverseNumbers.java public class ReverseNumbers { // // Reads a list of numbers from the user, storing them in an // array, then prints them in the opposite order. // public static void main (String[] args) { System.out.println (); } double[] numbers = new double[10]; System.out.println ("The size of the array: " + numbers.length); for (int index = 0; index < numbers.length; index++) numbers[index] = EasyInput.getDouble("Enter next number"); System.out.println ("The numbers in reverse:"); for (int index = numbers.length-1; index >= 0; index--) System.out.print (numbers[index] + " ");

unit 5 14 Array Declarations Revisited H The brackets of the array type can be associated with the element type or with the name of the array H Therefore the following declarations are equivalent: float[] prices; float prices[]; H The first format is generally more readable

unit 5 15 Shortcut: Initializer Lists H An initializer list can be used to instantiate and initialize an array in one step H The values are delimited by braces and separated by commas H Examples: int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] letterGrades = {'A', 'B', 'C', 'D', 'F'};

unit 5 16 Initializer Lists H Note that when an initializer list is used: the new operator is not used no size value is specified H The size of the array is determined by the number of items in the initializer list H An initializer list can only be used in the declaration of an array

unit 5 17 Arrays of Objects H The elements of an array can be object references  The following declaration reserves space to store 25 references to String objects String[] words = new String[25];  It does not create the String objects themselves H Each object stored in an array must be instantiated separately

unit 5 18 // GradeRange.java public class GradeRange { // // Stores the possible grades and their numeric lowest value, // then prints them out. // public static void main (String[] args) { String[] grades = {"A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "F"}; int[] cutoff = {95, 90, 87, 83, 80, 77, 73, 70, 67, 63, 60, 0}; for (int level = 0; level < cutoff.length; level++) System.out.println (grades[level] + "\t" + cutoff[level]); } } A95 A-90 B+87 B83 B-80 C+77 C73 C-70 D+67 D63 D-60 F0

unit 5 19 A A B - String[] grades { Organizing array of objects in memory …

unit 5 20 Array of objects Coin[] dimes = new Coin[10]; int face; face = dimes[1].getFace(); X dimes[1] = new Coin(); face = dimes[1].getFace();

unit 5 21 Command-Line Arguments  The signature of the main method indicates that it takes an array of String objects as a parameter public static void main (String[] args) H These values come from command-line arguments that are provided when the interpreter is invoked  For example, the following invocation of the interpreter passes an array of three String objects into main: > java VoteRecount Florida New-Mexico Oregon H These strings are stored in args[0], args[1] and args[2] respectively

unit 5 22 Array members of Objects H Objects can have arrays as instance variables H Therefore, fairly complex structures can be created simply with arrays and objects H The software designer must carefully determine an organization of data and objects that makes sense for the situation

unit 5 23 Arrays as Parameters H A reference to an array can be passed to a method as a parameter H Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other H As the method access the array through an alias reference, the content of the array can be changed H An array element can be passed to a method like any other value

unit 5 24 Example: class Polynom // A polynom is a real valued function of the // form f(x)=a 0 +a 1 x+a 2 x a n x n. public class Polynom { // The coefficients of the polynom // coefficients[i] is the coefficient of x i private double[] coefficients; // Constructs a polynom with a given set // of coefficients. public Polynom(double[] coefficients) { this.coefficients = new double[coefficients.length]; for (int i=0; i<coefficients.length; ++i) this.coefficients[i] = coefficients[i]; }

unit 5 25 Class Polynom service method 1 // Computes the value of the polynom for given point the value of the polynom at x public double valueAt(double x) { double value = 0.0; double power = 1.0; for (int i=0; i<coefficients.length; i++) { value += coefficients[i]*power; power *= x; } return value; }

unit 5 26 Class Polynom service method 2 // Returns the degree of the polynom public int getDegree() { int degree = coefficients.length-1; while (coefficients[degree]==0.0) { degree--; } return degree; }

unit 5 27 Class Polynom service method 3 // Computes the polynom resulting from the addition // of this polynom and another polynom. public Polynom add(Polynom p) { return new Polynom(coeffs); } int degree = Math.max(getDegree(), p.getDegree()); int degmin = Math.min(getDegree(), p.getDegree()); double[] coeffs = new double[degree]; for (int i=0; i<degmin; i++) coeffs[i] = coefficients[i] + p.coefficients[i]; for (int i=degmin; i<degree; i++) if (getDegree()<p.getDegree()) coeffs[i] = coefficients[i]; else coeffs[i] = p.coefficients[i];

unit 5 28 Using class polynom // Prints a table of values for x 3 -2x 2 +5x+7; class PolynomUseExample { static final double LOWER_LIMIT = -5.0; static final double UPPER_LIMIT = 5.0; static final double STEP = 1.0; public static void main(String[] args) { double[] coefficients = {7.0, 5.0, -2.0, 1.0}; Polynom p = new Polynom(coefficients); for (double x=LOWER_LIMIT; x<=UPPER_LIMIT; x+=STEP) System.out.println(x + ” \t “ + p.valueAt(x)); } }

unit 5 29 Two-Dimensional Arrays H A one-dimensional array stores a simple list of values H A two-dimensional array can be thought of as a table of values, with rows and columns H A two-dimensional array element is referenced using two index values H To be precise, a two-dimensional array in Java is an array of arrays

unit 5 30 Array of arrays double[][] samples; samples = new double[6][]; samples[0] = new double[2]; samples[1] = new double[1]; for (int i=2; i<samples.length; i++) samples[i] = new double[i+1];

unit 5 31 class Table2D { public static void main(String[] args) { int[][] table2D = new int[4][]; table2D[0] = new int[7]; table2D[1] = new int[6]; table2D[2] = new int[8]; table2D[3] = new int[7]; for (int j=0; j<table2D.length; j++) { for (int i=0; i<table2D[j].length; i++) System.out.print(table2D[j][i]); System.out.println(); } } } 47687

unit 5 32 Two dimensional array double[][] samples; samples = new double[6][6];

unit 5 33 Example: class Matrix // A matrix of real numbers public class Matrix { // The elements of the matrix private double[][] elements; // Construct new matrix from table of values public Matrix(double[][] elements) { int height = elements.length; int width = elements[0].length; this.elements = new double[height][width]; for (int i=0; i<height; ++i) for (int j=0; j<width; ++j) this.elements[i][j] = elements[i][j]; } }

unit 5 34 Class Matrix service methods // Returns the number of rows of the matrix public int numberOfRows() { return elements.length; } // Returns the number of columns of the matrix public int numberOfColumns() { return elements[0].length; } // Returns element (i,j) of the matrix public double getElement(int i, int j) { return elements[i][j]; }

unit 5 35 Class Matrix service methods Class Matrix service methods public Matrix multiply(Matrix a) { int n = numberOfRows(); int m = numberOfColumns(); int l = a.numberOfColumns(); double[][] result = new double[n][l]; for (int i=0; i<n; i++) { for (int j=0; j<l; j++) { for (int k=0; k<m; k++) { result[i][j] += elements[i][k]*a.elements[k][j]; } } } return new Matrix(result); }

unit 5 36 Example: using class matrix class MatrixUse { public static void main(String[] args) { double[][] aElements = { { 1.0, 2.0}, {-3.0, 1.0} }; double[][] bElements = { { 3.0,-1.0}, {-2.0, 2.0} };

unit 5 37 Example: using class matrix Matrix a,b,c; a = new Matrix(aElements); b = new Matrix(bElements); c = a.multiply(b); for (int i=0; i<c.numberOfRows(); i++) { for (int j=0; j<c.numberOfColumns(); j++) { System.out.print(c.getElement(i,j)+” ”); } System.out.println(); } } }

unit 5 38 Multidimensional Arrays H An array can have as many dimensions as needed, creating a multidimensional array H Each dimension subdivides the previous one into the specified number of elements  Each array dimension has its own length member H Because each dimension is an array of array references, the arrays within one dimension could be of different length

unit 5 39 The Vector Class  An object of class Vector is similar to an array in that it stores multiple values H However, a vector only stores objects does not have the indexing syntax that arrays have  The methods of the Vector class are used to interact with the elements of a vector  The Vector class is part of the java.util package  See Beatles.java (page 304) Beatles.java

unit 5 40 The Vector Class H An important difference between an array and a vector is that a vector can be thought of as a dynamic, able to change its size as needed H Each vector initially has a certain amount of memory space reserved for storing elements H If an element is added that doesn't fit in the existing space, more room is automatically acquired