Chapter 7: Arrays CS 121. April 9, Department of Computer Science College of Engineering Boise State University. Chapter 7: Arrays CS / 41

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

H212 Introduction to Software Systems Honors

CSC Java Programming, Fall Java Data Types and Control Constructs

&KDSWHU$UUD\VDQG9HFWRUV

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

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

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

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

Assignment 1 is due tonight at 11:59pm. Assignment 2 is due next Thursday at 11:59pm

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

Array. Prepared By - Rifat Shahriyar

CSC 1351: Quiz 6: Sort and Search

Introduction to Programming Using Java (98-388)

Computational Expression

COMP 202. Programming With Arrays

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

CS 251 Intermediate Programming Java Basics

CS159 Midterm #1 Review

Arrays and ArrayLists. David Greenstein Monta Vista High School

2/2/18. Assignment 2 is due Wednesday 14 February at 11:59pm. Reading for Monday s lecture is the remainder of Chapter 7 and all of Chapter 8

Administration. Objects and Arrays. Objects. Agenda. What is an Object? What is a Class?

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

Final Exam CS 152, Computer Programming Fundamentals December 9, 2016

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

CSE 142 Su01 Final Exam Sample Solution page 1 of 7

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2014

CS1083 Week 2: Arrays, ArrayList

You will not be tested on JUnit or the Eclipse debugger. The exam does not cover interfaces.

CSCI 136 Written Exam #0 Fundamentals of Computer Science II Spring 2015

TOPICS TO COVER:-- Array declaration and use.

You must bring your ID to the exam.

Example: Computing prime numbers

Prelim 1. CS 2110, October 1, 2015, 5:30 PM Total Question Name True Short Testing Strings Recursion

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

Algorithmic Thinking and Structured Programming (in Greenfoot) Teachers: Renske Smetsers-Weeda Sjaak Smetsers Ana Tanase

CS201- Introduction to Programming Current Quizzes

Review: Array Initializer Lists

Objectives. Order (sort) the elements of an array Search an array for a particular item Define, use multidimensional array

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

APCS Semester #1 Final Exam Practice Problems

Topics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1)

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

CS 231 Data Structures and Algorithms, Fall 2016

Array Basics: Outline

Array. Array Declaration:

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

Introduction to Object-Oriented Programming

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice

YEAHtzee. Tuesday Nov Aamnah Khalid and Peter Maldonado

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Pace University. Fundamental Concepts of CS121 1

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

Chapter 4: Conditionals and Loops

Array Basics: Outline

13 th Windsor Regional Secondary School Computer Programming Competition

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

Chapter 9 Introduction to Arrays. Fundamentals of Java

Last Class. While loops Infinite loops Loop counters Iterations

Final Exam CS 152, Computer Programming Fundamentals December 5, 2014

Java Foundations Certified Junior Associate

COMP-202: Foundations of Programming. Lecture 5: Arrays, Reference Type, and Methods Sandeep Manjanna, Summer 2015

Review of Important Topics in CS1600. Functions Arrays C-strings

Computer Science is...

Last Class. More on loops break continue A bit on arrays

Chapter 4: Conditionals and Loops

CS 139 Practice Midterm Questions #2

1B1b Classes in Java Part I

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Question 0. (1 point) Write the correct ID of the section you normally attend on the cover page of this exam if you have not already done so.

Introduction to Object-Oriented Programming

Arrays in Java Multi-dimensional Arrays

Chapter 12: Arrays Think Java: How to Think Like a Computer Scientist by Allen B. Downey

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

AP Computer Science Lists The Array type

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

COMP 110 Programming Exercise: Simulation of the Game of Craps

COMP More About Arrays. Yi Hong June 05, 2015

Arrays. Chapter 7. Walter Savitch Frank M. Carrano

today cs3157-fall2002-sklar-lect05 1

CSSE 220. Arrays, ArrayLists, Wrapper Classes, Auto-boxing, Enhanced for loop. Check out ArraysListPractice from SVN

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Chapter 4: Conditionals and Loops

Java Programming: from the Beginning

EXCEPTIONS. Fundamentals of Computer Science I

The list abstract data type defined a number of operations that all list-like objects ought to implement:

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Midterm Exam CS 251, Intermediate Programming March 12, 2014

Practice exam for CMSC131-04, Fall 2017

Object Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang

STUDENT LESSON A12 Iterations

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

Arrays: Higher Dimensional Arrays. CS0007: Introduction to Computer Programming

CS 302: Introduction to Programming in Java. Lecture 12

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

H212 Introduction to Software Systems Honors

CS159. Nathan Sprague

Warm up question. 2)Which of the following operators are defined on a half integer? Which of the following would it be useful to write as behaviors?

Transcription:

Chapter 7: Arrays CS 121 Department of Computer Science College of Engineering Boise State University April 9, 2015 Chapter 7: Arrays CS 121 1 / 41

Topics Array declaration and use Bounds checking Arrays as objects Arrays of objects Go to part 1 Go to part 2 Go to part 3 Arrays as Method Parameters Command-line arguments Multi-dimensional arrays Go to part 0 Go to part 5 Go to part 6 Go to part 4 Chapter 7: Arrays CS 121 2 / 41

Arrays An array is an ordered list of values. Each array has a name by which it can be referenced. Each value (or element), of an array has a numeric index. Chapter 7: Arrays CS 121 3 / 41

Arrays In Java, arrays are indexed from 0 to n 1, where n is the number of elements in the array. For example, our scores array has 5 elements that are indexed from 0 4. Values stored in the same array must be of the same type the element type. The element type can be a primitive type (e.g. int, double, boolean etc.) or an object reference (e.g. String, Song, Card, etc.) In Java, the array itself is an object that must be instantiated using the new operator. Chapter 7: Arrays CS 121 4 / 41

Declaring Arrays The scores array could be declared as follows. int [ ] scores = new int[5] ; array creates a new type array object array name type and size LHS Declares the type of the scores variable as int[] (meaning, an array of int values). RHS Instantiates a new int[] (integer array) object of size 5. Chapter 7: Arrays CS 121 5 / 41

Declaring Arrays An array of letters char [] letters ; letters = new char [26]; An array of String objects String [] dictionary = new String [ 480000]; An array of Song objects Song [] playlist = new Song [3]; An array of Card objects Card [] deckofcards = new Card [52]; An array of boolean objects boolean [] lightswitches = new boolean [100]; Chapter 7: Arrays CS 121 6 / 41

Accessing Array Elements A particular value in an array can be referenced using its index in the array. For example, to access the second element of our scores array, we would use the expression scores [2] The value returned by the expression scores[i] is just an int. So, we can have expressions like, totalscore += scores [2]; scores [2] = 89; // Updates the value in the array scores [ count ] = scores [ count ] + 2; System. out. println (" High score : " + scores [3]) ; Chapter 7: Arrays CS 121 7 / 41

Using Arrays Typically, array elements are accessed using a for loop: // every array has a public constant called length // that stores the size of the array int totalscore = 0; for ( int i = 0; i < scores. length ; i ++) { totalscore += scores [ i]; } Or a for-each loop: int totalscore = 0; for ( int score : scores ) { totalscore += score ; } Chapter 7: Arrays CS 121 8 / 41

Using Arrays: Example /** * BasicArray. java - Demonstrates basic array declaration and use. * @author Java Foundations */ public class BasicArray { /** * Creates an array, fills it with various integer values, * modifies one value, then prints them out. */ public static void main ( String [] args ) { final int LIMIT = 15, MULTIPLE = 10; int [] list = new int [ LIMIT ]; // Initialize the array values for ( int index = 0; index < LIMIT ; index ++) list [ index ] = index * MULTIPLE ; list [5] = 999; // change one array value } } // Print the array values for ( int value : list ) System. out. print ( value + " "); Chapter 7: Arrays CS 121 9 / 41

Using Arrays: Example Chapter 7: Arrays CS 121 10 / 41

Bounds Checking When an array is created, it has a fixed size. The size of the array is provided by a public constant named length. When accessing an element of an array, we must use a valid index. For example, for an array scores, the range of valid indexes is 0 to scores.length - 1. What happens when we try to access something out of bounds? The Java interpreter throws an ArrayIndexOutOfBoundsException. This is called automatic bounds checking. Chapter 7: Arrays CS 121 11 / 41

Bounds Checking Recall our scores array. The valid index range is 0 to 4. Now, we want to print all values in our array using this loop: for ( int i = 0; i <= scores. length ; i ++) { System. out. println ( scores [i]); } Will this work? NO. The last iteration of our loop is trying to access the element at index 5. But it doesn t exist! We will get an exception... java ScoresArray 10 20 30 40 50 Exception in thread " main " java. lang. ArrayIndexOutOfBoundsException : 5 at ScoresArray. main ( ScoresArray. java :10) Chapter 7: Arrays CS 121 12 / 41

Bounds Checking Off-by-one errors are common when using arrays. Remember, the length constant stores the size of the array, not the largest index. The correct loop condition is for ( int i = 0; i < scores. length ; i ++) { System. out. println ( scores [i]); } Chapter 7: Arrays CS 121 13 / 41

Examples Example: ReverseOrder.java Reads a list of numbers from a user and prints it in the opposite order. Example: LetterCount.java Reads a sentence and prints the counts of lowercase and uppercase letters. Chapter 7: Arrays CS 121 14 / 41

In-class Exercise Write an array declaration for the ages of 100 children. Write a for loop to print the ages of the children Write a for-each loop to print the ages of the children Write a for loop to find the average age of these children, assuming that the array has been initialized. Chapter 7: Arrays CS 121 15 / 41

In-class Exercise What does the following code do? int [] array = new int [100]; for ( int i = 0; i < array. length ; i ++) array [ i] = 1; int [] temp = new int [200]; for ( int i = 0; i < array. length ; i ++) temp [i] = array [i]; What happens if we now assign temp to array? array = temp ; Chapter 7: Arrays CS 121 16 / 41

Arrays of Objects (1) The name of an array is an object reference variable: An array of objects really just holds object references. For example, the following declaration reserves space to store 5 references to String objects. String [] words = new String [5]; It does not create the String objects themselves. Initially, the array holds null references. We need to create the String objects. Chapter 7: Arrays CS 121 17 / 41

Arrays of Objects (2) After declaration. String [] words = new String [5]; After adding 3 strings. words [0] = " friendship "; words [1] = " loyalty "; words [2] = " honor "; Chapter 7: Arrays CS 121 18 / 41

Arrays of Objects (3) An array of coins. Coin [] wallet = new Coin [5]; for ( int i = 0; i< wallet. length ; i ++) wallet [i] = new Coin (); A collection of a hundred random die. Random rand = new Random (); Die [] dicecollection = new Die [100]; for ( int i = 0; i< dicecollection. length ; i ++) { int numfaces = rand. nextint (20) + 1; dicecollection [ i] = new Die ( numfaces ); } Chapter 7: Arrays CS 121 19 / 41

Arrays of Objects (4) Example: CD.java, CDCollection.java, Tunes.java Chapter 7: Arrays CS 121 20 / 41

Growing Arrays: A Space Time Tradeoff The size of an array is fixed at the time of creation. What if the array fills up and we want to add more elements? We can create a new array and copy the existing elements to the new array. In effect, we have grown the array. How much bigger should the new array be? Minimum space: We could grow the array by one elements so it can store the new element. Minimum time: Grow the array to the maximum size we will ever need. However, in many cases we don t know ahead of time how large the array needs to grow... Heuristic: A good heuristic is to double the size so we don t have to do the copying again and again. The ArrayList class grows an array internally. Example: GrowingArrays.java Chapter 7: Arrays CS 121 21 / 41

In-class Exercise Declare and instantiate an array of hundred Color objects. Color [] mycolors = new Color [100]; Now fill the array with random colors using a for loop. Random rand = new Random (); for ( int i = 0; i < mycolors. length ; i ++) { mycolors [i] = new Color ( rand. nextint (256), rand. nextint (256), rand. nextint (256) ); } Write an array declaration and any necessary supporting classes to represent credit card transactions that contain a transaction number, a merchant name, and a charge. Chapter 7: Arrays CS 121 22 / 41

Initializing Arrays An initializer list can be used to instantiate and fill an array in one step. For example, int [] scores = {91, 82, 78, 98, 86}; String [] fruit = {" apple ", " orange ", " banana "}; The new operator is not needed (it is implied). The size of the new array is determined by the number of items in the initializer list. Initializer lists can only be used in the array declaration. Initializer lists can contain expressions or objects (including calls to new to create objects). For example: Die [] mycollection = { new Die (10), new Die (20), new Die (20) }; Chapter 7: Arrays CS 121 23 / 41

Arrays as Method Parameters An entire array can be passed as a parameter to a method. Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other. Therefore, changing an array element within the method changes the original outside of the method. An individual array element can be passed to a method as well, in which case the type of the formal parameter is the same as the element type. Example: ArrayPassing.java Chapter 7: Arrays CS 121 24 / 41

Command-Line Arguments (1) A program can accept any number of arguments from the command line (known as command-line arguments). Allows the user to specify configuration information when the program is launched, instead of asking for it at run-time. For example, suppose a Java application called Sort sorts lines in a file. To sort the data in a file named friends.txt, a user would enter: java Sort friends.txt Chapter 7: Arrays CS 121 25 / 41

Command-Line Arguments (2) Recall: The main method takes an array of String objects as a parameter. public static void main ( String [] args ) {... } When an application is launched, the runtime system passes the command-line arguments to the application s main method via this array of String objects. In our previous example, the String array passed to the main method of the Sort application contains a single String: "friends.txt". Chapter 7: Arrays CS 121 26 / 41

Iterating Over Command-Line Arguments (1) The following program prints each element of the args array to the console. public class CommandLineEcho { public static void main ( String [] args ) { for ( String arg : args ) System. out. println ( arg ); } } If we execute the program as follows java CommandLineEcho monkey peanut banana We would get monkey peanut banana Chapter 7: Arrays CS 121 27 / 41

Iterating Over Command-Line Arguments (2) Note that the space character separates command-line arguments. To have all words interpreted as a single argument, we can enclose them in quotation marks. java CommandLineEcho "monkey peanut banana" Would give us monkey peanut banana Chapter 7: Arrays CS 121 28 / 41

Parsing Command-Line Arguments We always want to validate our command-line arguments and print an appropriate usage message to the user if they entered invalid arguements. Typically, we want to validate the number of arguments the type of arguments the values are within a specific range Let s say we have a program that accepts a filename (String) followed by the number of characters per line (int). The number of characters per line must be between 1 and 80. Example: CommandLineValidation.java Chapter 7: Arrays CS 121 29 / 41

Parsing Numeric Command-Line Arguments In many cases, our command-line arguments will need to support numeric arguments. To handle this, we need to convert a String argument to a numeric value. int firstarg ; if ( args. length > 0) { try { firstarg = Integer. parseint ( args [0]) ; } catch ( NumberFormatException e) { System. err. println (" Argument " + args [0] + " must be an integer."); System. exit (1) ; } } parseint throws a NumberFormatException if the format of args[0] isn t valid. All of the wrapper classes for primitive types have parsex methods that convert a String representing a number to an object of their type X. Chapter 7: Arrays CS 121 30 / 41

2-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. Chapter 7: Arrays CS 121 31 / 41

2-Dimensional Arrays (1) In Java, a 2-D array is an array of arrays. A 2-D array is declared by specifying the size of each dimension separately. int [][] table = new int [3][5]; An array element is referenced using two index values int value = table [1][3]; Note that table.length is the number of rows in the table. Note that table[i].length is the length of the ith row in the table Chapter 7: Arrays CS 121 32 / 41

2-Dimensional Arrays (2) In-class Exercise. What does the following 2-d array contain after the code executes? int numrows = 3, numcols = 5; int [][] table = new int [ numrows ][ numcols ]; for ( int row = 0; row < numrows ; row ++) for ( int col = 0; col < numcols ; col ++) table [ row ][ col ] = row ; In-class Exercise. What if we change the initialization? for ( int row = 0; row < numrows ; row ++) for ( int col = 0; col < numcols ; col ++) table [ row ][ col ] = row * numcols + col ; Chapter 7: Arrays CS 121 33 / 41

2-Dimensional Arrays (3) In-class Exercise. What does the following method do? public static void printarray ( int arr [][]) { for ( int i = 0; i < arr. length ; i ++) { for ( int j = 0; j < arr [i]. length ; j ++) System. out. print ( arr [i][j] + " "); System. out. println (); } System. out. println (); } Example: TwoDimArrays.java Chapter 7: Arrays CS 121 34 / 41

2-Dimensional Arrays (3) Since a 2-dimensional array is an array of arrays, we can declare it in two parts: int [][] table = new table [3][]; //2nd dim blank for ( int i = 0; i < table. length ; i ++) table [ i] = new int [5]; Layout of a 2-dim array in memory: Chapter 7: Arrays CS 121 35 / 41

2-Dimensional Arrays (4) Two-dimensional arrays don t have to be square or rectangular in shape! Example: FunkyArrays.java In-class Exercise What does the following code do? Color [][] board = new Color [8][8]; for ( int row = 0; row < board. length ; row ++) { for ( int col = 0; col < board [ row ]. length ; col ++) { if ( row % 2 == col % 2) board [ row ][ col ] = Color. white ; else board [ row ][ col ] = Color. red ; } } Chapter 7: Arrays CS 121 36 / 41

Multi-Dimensional Arrays (1) Any array with more than one dimension is a multi-dimensional 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. Chapter 7: Arrays CS 121 37 / 41

Multi-Dimensional Arrays (2) Arrays can have more than two-dimensions. Here is a declaration for a 3-dimensional array. double [][][] data = new double [4][1000][100]; Can you think of when a 3-D array might be useful? A spreadsheet is a 2-dimensional array. The tabs would make it 3-dimensional. Simulations of liquids, solids, space etc. Modeling in science and engineering. A 4-D array? (not very common...) Instead of building larger dimensional arrays, it is a better design to have arrays of objects such that the objects contain arrays inside them as needed to get the dimensional depth. Chapter 7: Arrays CS 121 38 / 41

Multi-Dimensional Arrays (3) Consider a 3-dim array to represent a universe that has a 100 galaxies. Suppose that each galaxy has a 1000 star clusters. Each cluster has 10 stars. Star [][][] myuniverse = new Star [100][1000][10]; public class Star {... } Here is a different design that avoids the multidimensional array. Galaxy [] myuniverse = new Galaxy [100]; public class Galaxy { private Cluster [] myclusters = new Cluster [1000]; // other related instance variables } public class Cluster { private Star [] mystars = new Star [10]; // other related instance variables } public class Star {... } Chapter 7: Arrays CS 121 39 / 41

In-class Exercise How would we implement an ArrayList<String>? How would we implement the following operations? add(string element): adds an element to the end of the array list add(string element, int index): adds an element at the indexth position remove(int index): removes an element at the indexth position contains(string s): returns true if the array list contains the string s Chapter 7: Arrays CS 121 40 / 41

Exercises Read Chapter 7 (skip Section 7.5). Recommended Homework: Exercises: EX 7.1, 7.4 (e), 7.5, 7.8. Projects: PP 7.1, 7.2, 7.5. Browse: Sections 6.1. Chapter 7: Arrays CS 121 41 / 41