Arrays - Review. Two-Dimensional Arrays. Arrays, Part 2. Dr. Papalaskari 1. CSC 1051 Data Structures and Algorithms I

Similar documents
CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Arrays - Review. Initializer Lists. The for-each Loop. Arrays, Part 2. Dr. Papalaskari 1. CSC 1051 Data Structures and Algorithms I

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Arrays - Review. Arrays as Parameters. Arrays as Parameters. Arrays and File Input. Dr. Papalaskari 1. CSC 1051 Data Structures and Algorithms I

Arrays and File Input

Arrays and File Input

CSC 2014 Java Bootcamp. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Arrays, Part 3: Multidimensional arrays

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

Chapter 8 Arrays. Java Software Solutions. Foundations of Program Design Seventh Edition. John Lewis William Loftus

Java Bootcamp - Villanova University. CSC 2014 Java Bootcamp. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 1051 Algorithms and Data Structures I. Final Examination December 20, Name: KEY. Question Value Score

Chapter 7. Arrays are objects that help us organize large amounts of information

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

H212 Introduction to Software Systems Honors

7.3 Arrays of Strings (Objects) 7.3 Arrays of Strings (Objects) 7.3 Tunes.java. 7.3 Arrays of Objects 9/11/13. ! A UML diagram for the Tunes program

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

CSC 1051 Data Structures and Algorithms I

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name: Question Value Score

Introduction to Arrays

Arrays. Outline 1/7/2011. Arrays. Arrays are objects that help us organize large amounts of information. Chapter 7 focuses on:

Selection Statements and operators

CSC 1051 Arrays - Review questions

Selection Statements and operators

Happy Cinco de Mayo!!!!

CSC 1051 Algorithms and Data Structures I. Final Examination May 12, Name: KEY. Question Value Score

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 1051 Algorithms and Data Structures I. Final Examination May 12, Name

Selection and Repetition Revisited

Happy Cinco de Mayo!!!!

Arrays Chapter 7. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Designing Classes. Where do objects come from? Where do objects come from? Example: Account datatype. Dr. Papalaskari 1

class declaration Designing Classes part 2 Getting to know classes so far Review Next: 3/18/13 Driver classes:

Where do objects come from? Good question!

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

&KDSWHU$UUD\VDQG9HFWRUV

CSC 1051 Data Structures and Algorithms I

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Selection and Repetition Revisited

Algorithms and Conditionals

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Arrays in Java Multi-dimensional Arrays

Selection and Repetition

Iterators and File Input

COMP 202. Programming With Arrays

CSC 1051 Algorithms and Data Structures I. Final Examination December 17, Name:

Chapter 6: Arrays. Presentation slides for. Java Software Solutions. for AP* Computer Science 3rd Edition

b[0] = 1 b[1] = 2 b[2] = 3 b[3] = 4 b[4] = 5 c[0] = 2 c[1] = 3 c[2] = 4 c[3] = 5 c[4] = 6

11/19/2014. Arrays. Chapter 6: Arrays. Arrays. Arrays. Java Software Solutions for AP* Computer Science A 2nd Edition

Using Classes and Objects

CSC 1051 Data Structures and Algorithms I

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 7, Name:

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Basics of Java Programming variables, assignment, and input

Selection and Repetition

Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Designing Classes part 2

Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Java I/O and Control Structures

Lecture 3: Variables and assignment

Conditional Statements

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Java I/O and Control Structures Algorithms in everyday life

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Improved algorithm. Java code. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm

Java code. Updated program. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm. Improved algorithm

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 25, Name: KEY A

Designing Classes. Where do objects come from? Where do objects come from? Example: Account datatype. Dr. Papalaskari 1

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

COMP 202. Programming With Arrays

Control flow, conditionals, boolean expressions, block statements, nested statements. Course website:

University of Palestine. Mid Exam Total Grade: 100

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

AP Computer Science A Unit 7. Notes on Arrays

Lesson 9: Introduction To Arrays (Updated for Java 1.5 Modifications by Mr. Dave Clausen)

COMP More About Arrays. Yi Hong June 05, 2015

AP CS Unit 7: Arrays Exercises

2: Basics of Java Programming

Java: Classes. An instance of a class is an object based on the class. Creation of an instance from a class is called instantiation.

CS Computers & Programming I Review_01 Dr. H. Assadipour

CMPT 126: Lecture 6 Arrays

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

ESC101 : Fundamental of Computing

COE 211 Computer Programming. Welcome to Exam I Tuesday March 13, 2018

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

Array indexing. Before we use an array, we have to declare it. For example, int[] height=new int[11];

Lab Assignment Three

Lab 5. Name: Checked: Part A. Focus on Strings

Chapter 8 Multi-Dimensional Arrays

File I/O and Exceptions

Chapter 6 Arrays, Part D 2d Arrays and the Arrays Class

Computer Science II (20082) Week 1: Review and Inheritance

COE 212 Engineering Programming. Welcome to the Final Exam Tuesday December 15, 2015

CSC Algorithms and Data Structures I. Midterm Examination February 25, Name:

Transcription:

Arrays, Part 2 CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this presentation are adapted from the slides accompanying Java Software Solutions by Lewis & Loftus Arrays - Review Declaration: The entire array has a single name scores double[] scores index array element scores[2] 7.9 8.7 9.4 8.2 6.7 9.8 8.7 8.1 7.4 9.1 Size of array scores.length 10 element type Instantiation: = new double[10]; Initialization: scores[0] = 7.9; scores[1] = 8.7; scores[2] = 9.4; scores[3] = 8.2; scores[4] = 6.7; scores[5] = 9.8; scores[6] = 8.7; scores[7] = 8.1; scores[8] = 7.4; scores[9] = 9.1; Declaration, Instantiation, & Initialization combined: double[] scores = 7.9, 8.7, 9.4, 8.2, 6.7, 9.8, 8.7, 8.1, 7.4, 9.1; Two-Dimensional Arrays A one-dimensional array stores a list of elements A two-dimensional array can be thought of as a table of elements, with rows and columns declaration 2D Array Example double[][] coursegrade = new double[3][10]; coursegrade 2D array element coursegrade[1][4] 7.9 8.7 9.4 8.2 6.7 9.8 8.7 8.1 7.4 9.1 one dimension two dimensions 0 1 2 9.3 5.8 6.9 5.5 9.0 8.3 7.7 9.2 9.8 8.2 8.9 8.0 8.4 6.2 7.7 7.3 9.6 6.1 7.8 7.3 array element (a row) coursegrade[2] Dr. Papalaskari 1

2D Array Example from textbook TwoDArray.java Author: Lewis/Loftus Demonstrates the use of a two-dimensional array. public class TwoDArray Creates a 2D array of integers, fills it with increasing integer values, then prints them out. int[][] table = new int[5][10]; Load the table with values for (int row=0; row < table.length; row++) for (int col=0; col < table[row].length; col++) table[row][col] = row * 10 + col; Print the table for (int row=0; row < table.length; row++) for (int col=0; col < table[row].length; col++) System.out.print (table[row][col] + "\t"); System.out.println(); 2D Array Example from textbook TwoDArray.java Author: Lewis/Loftus Demonstrates the use of a two-dimensional array. Output public class TwoDArray 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 Creates a 2D array of integers, fills it with increasing 40 41 42 43 44 45 46 47 48 49 integer values, then prints them out. int[][] table = new int[5][10]; Load the table with values for (int row=0; row < table.length; row++) for (int col=0; col < table[row].length; col++) table[row][col] = row * 10 + col; Print the table for (int row=0; row < table.length; row++) for (int col=0; col < table[row].length; col++) System.out.print (table[row][col] + "\t"); System.out.println(); Two-Dimensional Arrays Types? Expression Type Description table int[][] 2D array of integers, or array of integer arrays table[5] int[] array of integers table[5][12] int integer Another 2D Array Example from textbook SodaSurvey.java Author: Lewis/Loftus Demonstrates the use of a two-dimensional array. import java.text.decimalformat; public class SodaSurvey Determines and prints the average of each row (soda) and each column (respondent) of the survey scores. public static void main(string[] args) int[][] scores = 3, 4, 5, 2, 1, 4, 3, 2, 4, 4, 2, 4, 3, 4, 3, 3, 2, 1, 2, 2, 3, 5, 4, 5, 5, 3, 2, 5, 5, 5, 1, 1, 1, 3, 1, 2, 1, 3, 2, 4 ; final int SODAS = scores.length; final int PEOPLE = scores[0].length; int[] sodasum = new int[sodas]; int[] personsum = new int[people]; Dr. Papalaskari 2

Another 2D Array Example from textbook for (int soda=0; soda < SODAS; soda++) for (int person=0; person < PEOPLE; person++) sodasum[soda] += scores[soda][person]; personsum[person] += scores[soda][person]; DecimalFormat fmt = new DecimalFormat ("0.#"); System.out.println ("Averages:\n"); for (int soda=0; soda < SODAS; soda++) System.out.println ("Soda #" + (soda+1) + ": " + fmt.format ((float)sodasum[soda]/people)); Output Averages: System.out.println (); for (int person=0; person < PEOPLE; person++) System.out.println ("Person #" + (person+1) + ": " + fmt.format ((float)personsum[person]/sodas)); Soda #1: 3.2 Soda #2: 2.6 Soda #3: 4.2 Soda #4: 1.9 Person #1: 2.2 Person #2: 3.5 Person #3: 3.2 Person #4: 3.5 Person #5: 2.5 Person #6: 3 Person #7: 2 Person #8: 2.8 Person #9: 3.2 Person #10: 3.8 Multidimensional Arrays An array can have many dimensions if it has more than one dimension, it is called a multidimensional array Each dimension subdivides the previous one into the specified number of elements Each dimension has its own length constant Because each dimension is an array of array references, the arrays within one dimension can be of different lengths these are sometimes called ragged arrays Managing a collection of objects Example: a Movie database (collection of DVD objects) DVD.java Author: Lewis/Loftus/Papalaskari Represents a DVD video disc. (*** modified from textbook version ***) ********************************************************************im port java.text.numberformat; public class DVD private String title, director; private int year; private double cost; private boolean bluray; Constructor: Creates a new DVD with the specified information. public DVD(String title, String director, int year, double cost, boolean bluray) this.title = title; this.director = director; this.year = year; this.cost = cost; this.bluray = bluray; Dr. Papalaskari 3

Returns a string description of this DVD. public String tostring() NumberFormat fmt = NumberFormat.getCurrencyInstance(); String description; description = fmt.format(cost) + "\t" + year + "\t"; description += title + "\t" + director; Test client create a few DVDs, print their info: TestDVD.java Author: M A Papalaskari Test client for DVD.java public class TestDVD Creates some DVD objects and prints their info public static void main(string[] args) if (bluray) description += "\t" + "Blu-Ray"; return description; DVD one = new DVD("Casablanca", "Michael Curtiz", 1942, 19.95, false); DVD two = new DVD("District 9", "Neill Blomkamp", 2009, 19.95, false); DVD three = new DVD("Iron Man", "Jon Favreau", 2008, 15.95, false); System.out.println (one); System.out.println (two); System.out.println (three); What if we want to store more DVDs? MyTenMovies.java Author: M A Papalaskari Test client for DVD.java public class MyTenMovies Creates some DVD objects and prints their info public static void main(string[] args) DVD[] list = new DVD[10]; Use an array of DVD objects: list[0] DVD one = new DVD("Casablanca", "Michael Curtiz", 1942, 19.95, false); list[1] DVD two = new DVD("District 9", "Neill Blomkamp", 2009, 19.95, false); list[2] DVD three = new DVD("Iron Man", "Jon Favreau", 2008, 15.95, false); System.out.println (one); for System.out.println (DVD item: list) (two); System.out.println System.out.println (three); (item); Next: A collection of DVD s that can grow to accommodate as many items as needed! No limit like this: DVD[] list = new DVD[10]; Dr. Papalaskari 4

Managing a collection of objects Example: a Movie database (collection of DVD objects) Movies.java DVDCollection.java Movies.java Author: Lewis/Loftus Demonstrates the use of an array of objects. public class Movies Creates a DVDCollection object and adds some DVDs to it. Prints reports on the status of the collection. public static void main(string[] args) DVDCollection movies = new DVDCollection(); movies.adddvd("the Godfather", "Francis Ford Coppala", 1972, 24.95, true); movies.adddvd("district 9", "Neill Blomkamp", 2009, 19.95, false); movies.adddvd("iron Man", "Jon Favreau", 2008, 15.95, false); movies.adddvd("all About Eve", "Joseph Mankiewicz", 1950, 17.50, false); movies.adddvd("the Matrix", "Andy & Lana Wachowski", 1999, 19.95, true); DVD.java movies.adddvd("iron Man 2", "Jon Favreau", 2010, 22.99, false); movies.adddvd("casablanca", "Michael Curtiz", 1942, 19.95, false); Movies.java Output Author: Lewis/Loftus Demonstrates ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ the use of an array of objects. My DVD Collection public class Movies Number of DVDs: 5 Total cost: $98.30 Average Creates cost: a DVDCollection $19.66 object and adds some DVDs to it. Prints reports on the status of the collection. DVD List: $24.95 1972 The Godfather Francis Ford Coppala Blu-Ray DVDCollection movies = new DVDCollection(); $19.95 2009 District 9 Neill Blomkamp $15.95 movies.adddvd 2008 ("The Iron Godfather", Man "Francis Jon Favreau Ford Coppala", 1972, 24.95, true); $17.50 movies.adddvd 1950 ("District All About 9", Eve "Neill Joseph Blomkamp", Mankiewicz 2009, 19.95, false); $19.95 movies.adddvd 1999 ("Iron The Matrix Man", "Jon Favreau", Andy & Lana 2008, Wachowski 15.95, false); Blu-Ray movies.adddvd ("All About Eve", "Joseph Mankiewicz", 1950, 17.50, false); movies.adddvd ("The Matrix", "Andy & Lana Wachowski", 1999, 19.95, true); movies.adddvd("iron Man 2", "Jon Favreau", 2010, 22.99, false); movies.adddvd("casablanca", "Michael Curtiz", 1942, 19.95, false); Movies.java Output Author: Lewis/Loftus Demonstrates ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ the use of an array of objects. My DVD Collection Output (d) public class Movies Number of DVDs: 5 Total ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ cost: $98.30 Average Creates My DVD cost: a DVDCollection $19.66 object and adds some DVDs to it. Prints reports on the status of the collection. DVD List: Number of DVDs: 7 public static Total void cost: main $141.24 (String[] args) $24.95 Average 1972 cost: The Godfather $20.18 Francis Ford Coppala Blu-Ray DVDCollection movies = new DVDCollection(); $19.95 2009 District 9 Neill Blomkamp $15.95 movies.adddvd 2008 List: ("The Iron Godfather", Man "Francis Jon Favreau Ford Coppala", 1972, 24.95, true); $17.50 movies.adddvd 1950 ("District All About 9", Eve "Neill Joseph Blomkamp", Mankiewicz 2009, 19.95, false); $19.95 movies.adddvd $24.95 1999 1972 ("Iron The Matrix Man", The Godfather "Jon Favreau", Andy Francis & Lana 2008, Wachowski 15.95, Ford Coppala false); Blu-Ray Blu-Ray movies.adddvd $19.95 2009 ("All About District Eve", "Joseph 9 Neill Mankiewicz", Blomkamp 1950, 17.50, false); movies.adddvd ("The Matrix", "Andy & Lana Wachowski", 1999, 19.95, true); $15.95 2008 Iron Man Jon Favreau $17.50 1950 All About Eve Joseph Mankiewicz System.out.println (movies); $19.95 1999 The Matrix Andy & Lana Wachowski Blu-Ray movies.adddvd $22.99 2010 ("Iron Man Iron 2", Man "Jon 2 Favreau", Jon Favreau 2010, 22.99, false); movies.adddvd $19.95 1942 ("Casablanca", Casablanca "Michael Curtiz", Michael 1942, Curtiz 19.95, false); Dr. Papalaskari 5

DVDCollection.java Author: Lewis/Loftus/Papalaskari Represents a collection of DVD objects (*** modified from textbook version ***) import java.text.numberformat; public class DVDCollection private DVD[] collection; private int count; Constructor: Creates an initially empty collection. public DVDCollection() collection = new DVD[100]; count = 0; Adds a DVD to the collection, using information from a String and increasing the size of the collection array if necessary. public void adddvd(string info) if (count == collection.length) increasesize(); collection[count] = new DVD(info); count++; Adds a DVD to the collection, increasing the size of the collection array if necessary. public void adddvd(string title, String director, int year, double cost, boolean bluray) if (count == collection.length) increasesize(); collection[count] = new DVD(title, director, year, cost, bluray); count++; Returns a report describing the DVD collection. public String tostring() NumberFormat fmt = NumberFormat.getCurrencyInstance(); String report = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; report += "My DVD Collection\n\n"; report += "Number of DVDs: " + count + "\n"; report += "\n\ndvd List:\n\n"; for (int i = 0; i < count; i++) report += collection[i].tostring() + "\n"; Increases the capacity of the collection by creating a larger array and copying the existing collection into it. private void increasesize() DVD[] temp = new DVD[collection.length * 2]; for (int i = 0; i < collection.length; i++) temp[i] = collection[i]; collection = temp; return report; Dr. Papalaskari 6

Arrays, Part 2 Arrays as Parameters An entire array can be passed as a parameter to a method (just like any other object). For example: Draws a triangle and a V-shape using polygons and polylines. public void paintcomponent(graphics page) super.paintcomponent(page); int[] xpoints = 100, 120, 150; int[] ypoints = 150, 40, 110; Assumes a definition for method average(), for example: page.setcolor(color.cyan); page.fillpolygon(xpoints, ypoints, xpoints.length); page.setcolor(color.red); page.drawpolyline(xpoints, ypoints, xpoints.length); Example: A method that adds 3 to the value of each element in an array of type int[]. public void addthree(int[] a) for (int i = 0; i < a.length; i++) a[i] += 3; see TrianglePanel.java Try this: Write a method that adds n (an int) to the value of each element in an array of type int[]. Command-Line Arguments It turns out we have been using arrays as parameters all along! Try this method with the TrianglePanel: invoke it with the array xpoints add code to draw another triangle in a different color, using the updated array xpoints Dr. Papalaskari 7

Command-Line Arguments It turns out we have been using arrays as parameters all along! public class Test System.out.println (); System.out.println (" " + args[0]); System.out.println (" " + args[1]); These values come from command-line arguments that are provided when the interpreter is invoked jgrasp calls them Run Arguments What does it mean to copy an array? Suppose we have two arrays: int[] a = 147, 323, 89, 933; int[] b = 100, 200, 300, 400; Copying elements vs. copying array variables: for (int i=0; i<a.length; i++) a[i] = b[i]; Afterwards, what is the effect of the following? a[1] = 1000; b[2] = 2000; a = b; 1) Copying elements: 2) Copying array variables: a 0 1 2 3 a 0 1 2 3 147 323 89 933 147 323 89 933 b 0 1 2 3 b 0 1 2 3 100 200 300 400 100 200 300 400 What changes? for (int i=0; i<a.length; i++) a[i] = b[i]; a[1] = 0; b[2] = 0; What a = b; changes? a[1] = 0; b[2] = 0; Dr. Papalaskari 8

Array parameters revisited How is using an array as a parameter like copying an array? Draws a triangle and a V-shape using polygons and polylines. public void paintcomponent(graphics page) super.paintcomponent(page); int[] xpoints = 100, 120, 150; int[] ypoints = 150, 40, 110; page.setcolor(color.cyan); page.fillpolygon(xpoints, ypoints, xpoints.length); addthree(xpoints); page.setcolor(color.red); page.drawpolyline(xpoints, ypoints, xpoints.length); public void addthree(int[] a) for (int i = 0; i < a.length; i++) a[i] += 3; Dr. Papalaskari 9