Introduction To Scientific Programming Chapter 6 – Arrays.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1 Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Arrays Chapter 6 Chapter 6.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CS102--Object Oriented Programming Lecture 5: – Arrays – Sorting: Selection Sort Copyright © 2008 Xiaoyan Li.
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.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
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.
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.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
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 9 Introduction to Arrays
Arrays Chapter 6 Array Basics Arrays in Classes and Methods
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
HST 952 Computing for Biomedical Scientists Lecture 5.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
Chapter 10Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 10 l Array Basics l Arrays in Classes and Methods l Programming.
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.
Lecturer: Dr. AJ Bieszczad Chapter 6 COMP 150: Introduction to Object-Oriented Programming 6-1 l Array Basics l Arrays in Classes and Methods l Programming.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
A First Book of ANSI C Fourth Edition
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
Chapter 10. Arrays Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Computer Programming with JAVA.
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.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
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.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
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,
Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.
Chapter 6 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays ** ** multidimensional.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
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 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Multidimensional Arrays l Vectors Multidimensional Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
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.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
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];
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.
EKT472: Object Oriented Programming
Arrays Chapter 6 Array Basics Arrays in Classes and Methods
1-Dimensional Arrays 2-Dimensional Arrays => Read section 1.4
Arrays.
Presentation transcript:

Introduction To Scientific Programming Chapter 6 – Arrays

S.Horton/107/Ch. 6Slide 2 Lecture Overview on Arrays I.Array Basics II.Arrays in Classes and Methods III.Sorting & Searching Arrays IV.Multidimensional Arrays

S.Horton/107/Ch. 6Slide 3 I. Array Basics An array is a single name for a collection of data values (all of the same data type) A special subscript notation identifies precisely one of the values of the collection Arrays work like objects: They are initialized like objects There can be multiple arrays of the same type Arrays are a natural fit for loops, especially for loops However, they are not “full” objects No real methods, constructors, or “inheritance”

S.Horton/107/Ch. 6Slide 4 Creating Arrays General syntax for declaring an array: Base_Type[] Array_Name = new Base_Type[Length]; Examples: 80-element array with base type char : char[] symbol = new char[80]; 100-element array with base type double : double[] reading = new double[100]; 100-element array with base type AddressBook : AddressBook[] homebook = new AddressBook[100];

S.Horton/107/Ch. 6Slide 5 Three Uses of [ ] (Brackets) with an Array Name 1. To create an array type name, e.g. int[] pressure; creates a name with the type " int array" The types int and “ int array” are different 2. To create a new array, e.g. pressure = new int[100]; 3. To name a specific element in the array (also called an indexed variable), e.g. pressure[3] = SavitchIn.readLineInt(); System.out.println("You entered" + pressure[3]);

S.Horton/107/Ch. 6Slide 6 An Array Declaration Can Be “Broken-Up” Last slide syntax was correct! Why? Because you can break up declaration like any object For example, the complete declaration: int[] pressure = new int[100]; can be broken up into: int[] pressure; // first part declaration … pressure = new int[100]; // second part assignment … This can be handy for re-declaration (more on this soon).

S.Horton/107/Ch. 6Slide 7 Array Terminology temperature[n + 2] temperature[n + 2] = 32; Array name Index (also called a subscript) - Must be an int, or an expression that evaluates to an int Indexed element/variable (also called a subscripted variable) Note: an "element" may refer to either a single indexed variable in the array or the value of a single indexed variable. Value of the indexed variable (also called an element of the array)

S.Horton/107/Ch. 6Slide 8 Array Length The length of an array is specified by the number given in the brackets when it is created with new This determines the maximum number of elements the array can hold and the amount of memory allocated for the elements The array length can always be read with the instance variable length. E.g. the following code displays the number 20 (this is the size, or length of the double array, entry ): double[] entry = new double[20]; //20*8 bytes allocated System.out.println(entry.length); The length attribute is established in the declaration and cannot be changed by the programmer unless the array is re-declared.

S.Horton/107/Ch. 6Slide 9 Subscript Range Any array subscript uses “zero-numbering” The first element has subscript 0 The second element has subscript 1 The n th element has subscript n-1 The last element has subscript length-1 For example: int[] score = new int[4]; … (Score is assigned values 97, 86, 92, and 71) … Configuration:

S.Horton/107/Ch. 6Slide 10 Subscript Issues & The “Out of Bounds” Error Using a subscript larger than length-1 causes a run-time (not a compiler) error An ArrayOutOfBoundsException is thrown You need to fix the problem and recompile Some other programming languages (most noticeably C and C++) do not even cause a run time error! It is a dangerous characteristic (of any language) to allow out of bounds array indexing. Why? Because bounds checking requires extra overhead. The most sophisticated compliers have the option to turn bounds checking on and off.

S.Horton/107/Ch. 6Slide 11 Initializing an Array's Values in Its Declaration Array declaration syntax allows element initialization by using a comma-delimited list in curly braces. To initialize an array, drop everything right of the equal sign and add the value list. For example: int[] score = {97, 86, 92, 71}; The length of an array is automatically determined when the values are explicitly initialized in the declaration. If an array is un-initialized, all elements will be assigned some default value, e.g. 0 for int arrays.

S.Horton/107/Ch. 6Slide 12 Initializing Array Elements in a Loop Array processing is most commonly done in a loop. A for loop is commonly used to initialize/work with arrays and array elements. Example: int i; // loop counter & array index int[] a = new int[10]; … For (i = 0; i < a.length; i++) a[i] = 0; The loop counter/array index goes from 0 to length – 1 Loop counts through 10 iterations using the zero- numbering of the array index (0-9).

S.Horton/107/Ch. 6Slide 13 Array Programming Tips Use singular rather than plural names for arrays unless the data itself is plural. This improves readability. For example: System.out.println(“The top score=” + score[index]); This is because, although the array contains many elements, an array used with a subscript references a single value. Do not count on default initial values for array elements You should explicitly initialize elements in the declaration or most commonly in a loop at the beginning of a method.

S.Horton/107/Ch. 6Slide 14 II. Arrays in Classes and Methods Arrays and array elements can be used with classes and methods just like other objects. Both an indexed array element and an array name can be an argument in a method. Both an indexed array element and an array name can be returned by a method.

S.Horton/107/Ch. 6Slide 15 An Indexed Array Element As A Method Argument nextScore is an array of int an element of nextScore is an argument of method average average method definition public static void main(String arg[]) { int i, firstScore; int[] nextScore = new int[3]; double possibleAverage; System.out.println("Enter your score on exam 1:"); firstScore = SavitchIn.readLineInt(); for (i = 0; i < nextScore.length; i++) nextScore[i] = *i; for (i = 0; i < nextScore.length; i++) { possibleAverage = ave(firstScore,nextScore[i]); System.out.println("If your score on exam 2 is " + nextScore[i]); System.out.println(" your average will be " + possibleAverage); } public static double ave(int n1, int n2) { return (n1 + n2)/2.0; }

S.Horton/107/Ch. 6Slide 16 When Can a Method Change an Indexed Array Element Argument? When an array element is a primitive type: A copy of the value is passed as an argument in method call So, the method cannot change the value of the indexed array element This follows the “call-by-value” convention When an array element is a class type: The address of the object is passed as an argument in method call So, the method can change the value of the indexed array element This follows the “call-by-reference” convention Note: the corresponding argument in the method definition becomes just another name for the object

S.Horton/107/Ch. 6Slide 17 Array Names as Method Arguments When you want to pass an entire array as an argument to a method, just use the array name and no brackets. As previously described, any method that gets a non- primitive type (the entire array, in this case) has access to the original array and can change the value of its’ elements. Using the length attribute inside the method will handle needing to know the size of the array and avoid ArrayIndexOutOfBoundsException

S.Horton/107/Ch. 6Slide 18 Example: An Array as an Argument in a Method Call public static void showArray(char[] a) { int i; for(i = 0; i < a.length; i++) System.out.println(a[i]); } the method's argument is the name of an array of characters uses the length attribute to control the loop allows different size arrays and avoids index-out-of- bounds exceptions

S.Horton/107/Ch. 6Slide 19 The declaration of a program’s main method defines a parameter that is an array of type String : public static void main(String[] args) When you execute a program from the command line, all words after the class name will be passed to the main method in the args array. The following main method in the class TestProgram will print out the first two arguments it receives: Solving Another Mystery - Arguments for the main Method public static void main(String[] args) { System.out.println(“Options:“ + args[0] + “ “ + args[1]); }

S.Horton/107/Ch. 6Slide 20 Consider the following: int[] a = new int[3]; int[] b = new int[3]; With the code statement b = a; what do you get? Since a and b are reference types, you get the address of a assigned to the address of b (you basically give a the name b ). If you want to copy a to b, you need to use/write a clone method With the code if (b == a) … what do you compare? Since a and b are reference types, you check if the address of a and the address of b are the same (i.e. are they exact same object). If you want to check if the arrays are equal, you need to use/write an equals method. Issues With Reference Types

S.Horton/107/Ch. 6Slide 21 Example: Using = With Array Names int[] a = new int[3]; int[] b = new int[3]; for(int i; i < a.length; i++) a[i] = i; b = a; System.out.println(a[2] + " " + b[2]); a[2] = 10; System.out.println(a[2] + " " + b[2]); The output for this code will be: 2 10 This does not create a copy of array a ; it makes b another name for array a.

S.Horton/107/Ch. 6Slide 22 Example: Using == With Array Names int i; int[] a = new int[3]; int[] b = new int[3]; for(i; i < a.length; i++) a[i] = i; for(i; i < b.length; i++) b[i] = i; if(b == a) System.out.println("a equals b"); else System.out.println("a does not equal b"); a and b are both 3-element arrays of int all elements of a and b are assigned the value 0 tests if the addresses of a and b are equal, not if the array values are equal The output for this code will be " a does not equal b " because the addresses of the arrays are not equal.

S.Horton/107/Ch. 6Slide 23 Testing Two Arrays for Equality To test two arrays for equality you need to define an equals method Return true if and only the arrays have the same length and all corresponding values are equal Can you write a clone method now? public static boolean equals(int[] a, int[] b) { boolean match; if (a.length != b.length) match = false; else { match = true; //tentatively int i = 0; while (match && (i < a.length)) { if (a[i] != b[i]) match = false; i++; } return match; }

S.Horton/107/Ch. 6Slide 24 Methods That Return an Array Method vowels returns an array of type char[] The array newArray is not passed back, the address is passed back. Notice that the array name within the method is just another name for the original array c. c, newArray, and the return type of vowels are all the same type: char [] public class returnArrayDemo { public static void main(String arg[]) { char[] c; //typed but not allocated c = vowels(); for(int i = 0; i < c.length; i++) System.out.println(c[i]); } public static char[] vowels() { char[] newArray = new char[5]; newArray[0] = 'a'; newArray[1] = 'e'; newArray[2] = 'i'; newArray[3] = 'o'; newArray[4] = 'u'; return newArray; }

S.Horton/107/Ch. 6Slide 25 Wrapper Classes For Arrays Arrays can be made into objects by defining them in a class No special syntax, just define array in a class and add the appropriate structure Derives name from and similar in structure to wrapper classes for primitive types In a well-defined array wrapper class, one can: Make an array an instance variable Define accessor/mutator methods to read and write element values and parameters Define constructors Define.equals,.clone,.toString,.sort, … This strategy leads to a number of very important data structures that are discussed in Math 108 – linked lists, queues, stacks, hash tables, etc…

S.Horton/107/Ch. 6Slide 26 Watch For Partially Filled Arrays Sometimes only part of an array has been filled with valid data Array elements always contain something, whether you have written to them or not Elements which have not been written to contain unknown (or garbage) data so you should avoid reading them There is no automatic mechanism to detect how many elements have been filled – you need to keep track!

S.Horton/107/Ch. 6Slide 27 entry[0]Buy milk. entry[1]Call home. entry[2]Go to beach. entry[3] " " entry[4] " " countOfEntries - 1 garbage values Example: Partially Filled Array countOfEntries has a value of 3. entry.length has a value of 5. entry is an array of type String. countOfEntries is current size (pointer).

S.Horton/107/Ch. 6Slide 28 III. Sorting an Array One of the most common issues facing programmers is to sort one or more arrays You may need to: Sort numbers in ascending or descending order Sort characters or strings in alphabetic order Sort one array and rearrange another based on first sort There are many algorithms (or methods) to sort an array. Some of the most common are Selection sort, Quicksort, and Heapsort Sorting algorithms have a number of attributes Speed/Efficiency, Direction, Order Preservation, In-Place, etc..

S.Horton/107/Ch. 6Slide 29 Selection Sort Selection sort is one of the easiest to understand and program Also, one of the slowest – called O(n 2 )! Great for rearranging multiple arrays based on sorting one of them (think ) Pseudocode for Selection sort: For each index in the array Find the smallest value from the current index Swap current index value with smallest value

S.Horton/107/Ch. 6Slide 30 Selection Sort: Diagram of an Example Problem: sort this 10-element array of integers in ascending order: 1st iteration: smallest value is 3, its index is 4, swap a[0] with a[4] before: after: 2nd iteration: smallest value in remaining list is 5, its index is 6, swap a[1] with a[6] Etc. - only nine iterations are required since the last one will put the last two entries in place by swapping them if necessary.

S.Horton/107/Ch. 6Slide 31 Attributes Of Selection Sort The SelectionSort program in your book shows a class for sorting an array of int in ascending order. Algorithm attributes: Every indexed variable must has a value If the array has duplicate values, they are put in sequential positions (order preserving) Note: sorting was defined in terms of smaller tasks, such as "find the index of the smallest value" and “swap two elements” These “subtasks” are written as separate methods and are private because they are helper methods (external users are not expected to call them directly)

S.Horton/107/Ch. 6Slide 32 /************************************************** * Sorts an array of integers. Every indexed * variable of array a has a value. Requires helper * routines indexOfSmallest & swap. * * Output: a[0] <= a[1] <=... <= a[a.length - 1]. * **************************************************/ public static void sort(int[] a) { int index, indexOfNextSmallest; for (index = 0; index < a.length - 1; index++) { //Find the next smallest value from current position indexOfNextSmallest = indexOfSmallest(index, a); //Place the correct value in a[index] swap(index,indexOfNextSmallest, a); } Selection Sort Code

S.Horton/107/Ch. 6Slide 33 /************************************************** * Returns an index in array a of the minimum value * from a[startIndex] through a[a.length-1] * **************************************************/ private static int indexOfSmallest(int startIndex, int[] a) { int min = a[startIndex]; //Beginning min value int indexOfMin = startIndex; //Index of beginning min value int index; for (index = startIndex+1; index < a.length; index++) { //Find min from a[startIndex] through a[index] if (a[index] < min) { min = a[index]; indexOfMin = index; } return indexOfMin; } Selection Sort Code - II

S.Horton/107/Ch. 6Slide 34 /************************************************** * Swaps two elements in array a. * **************************************************/ private static void swap(int i, int j, int[] a) { int temp; temp = a[i]; a[i] = a[j]; a[j] = temp; //original value in a[i] } Selection Sort Code - III

S.Horton/107/Ch. 6Slide 35 Sorting Algorithm Tradeoffs There is always a tradeoff in sorting algorithms between efficiency and simplicity. Selection Sort is: Not very efficient: O(n 2 ) But, easy to code and make modifications Quicksort & Heapsort are: Very efficient: O(nlog(n)) But, more complicated and harder to modify Rule of thumb: If you have more than 100 elements, you should always use an efficient sorting algorithm.

S.Horton/107/Ch. 6Slide 36 Sorting in Java Sorting is so common that Java provides a library of routines to perform optimized O(nlog(n)) sorting and searching Import the package java.util.Arrays; There are a number of static methods to perform in- place sorting and searching, e.g. int[] ivalue = new int[1000]; … Arrays.sort(ivalue);

S.Horton/107/Ch. 6Slide 37 /************************************************** * Sorts two arrays of integers based on sorting a. * Every indexed variable of array a has a value. * Requires helper routines indexOfSmallest & swap. * * Output: a[0] <= a[1] <=... <= a[a.length - 1]. * Array b is sorted based on a **************************************************/ public static void sort(int[] a, int[] b) { int index, indexOfNextSmallest; for (index = 0; index < a.length - 1; index++) { //Find the next smallest value from current position indexOfNextSmallest = indexOfSmallest(index, a); //Place the correct value in a[index] swap(index,indexOfNextSmallest, a); swap(index,indexOfNextSmallest,b); } Bonus II - Selection Sort Code For Multiple Arrays

S.Horton/107/Ch. 6Slide 38 Searching an Array An equally common task to sorting an array is to find a particular value in an array. There are two basic approaches to searching an array for a particular value – sequential search or binary search. The two main issues with searching: How many times do you need to search? What do you do if the value is not found? An important extension to searching in an array is searching in two-dimensional arrays or tables.

S.Horton/107/Ch. 6Slide 39 Sequential Search A sequential search is the easiest to understand and program. If you are only going to do it once, it is also the fastest! Sequential search pseudocode: For each element in the array from the start If value is equal to current index element, return index If end of array is reached with no match, return 0 A sequential search of an array is an O(n) process.

S.Horton/107/Ch. 6Slide 40 Sequential Search Code /********************************************* * This routine performs a sequential search of * an array of integers. If ivalue is found, * The index is returned. If no match is found, * zero is returned. * * *********************************************/ public int ssearch(int[] a, int ivalue) { int i = 0; for (;i < a.length; i++) { if (a[i] = ivalue) return i; } return 0; }

S.Horton/107/Ch. 6Slide 41 Sequential Search Code /********************************************* public static void showTable(int[][] displayArray) { int row, column; for (row = 0; row < displayArray.length; row++) { System.out.print((row + 1) + " "); for (column = 0; column < displayArray[row].length; column++) System.out.print("$" + displayArray[row][column] + " "); System.out.println(); }

S.Horton/107/Ch. 6Slide 42 Searching An Array Multiple Times If you need to frequently search for items in an array, sequential searching is inefficient. A much quicker way is to use binary search. Binary searching uses a divide and conquer algorithm to quickly locate the value in roughly half the time of a sequential search. This type of searching is an O(n/2) process. The issue is that a binary search only works on sorted data. So, you must incur the extra overhead of sorting the data first before performing binary searches.

S.Horton/107/Ch. 6Slide 43 Searching in Java Java provides a library of routines to perform optimized searching. Import the same package as before: java.util.Arrays; To perform multiple, efficient searches: int[] ivalue = new int[1000]; int index1,index2,item1,item2,… ; … Arrays.sort(ivalue); … index1 = Arrays.binarySearch(ivalue,item1); index2 = Arrays.binarySearch(ivalue,item2);

S.Horton/107/Ch. 6Slide 44 IV. Multi-Dimensional Arrays The next logical extension to a one-dimensional array is a two-dimensional array and so on… Java handles multi-dimensional arrays by just adding an index for each dimension (an array’s rank is how many dimensions it has). A two-dimensional (2-D) array can be thought of as a table, grid, or matrix The first dimension can be thought of as a row The second dimension can be thought of as a column A cell or value is the intersection of a row and a column An array element corresponds to a cell in the table

S.Horton/107/Ch. 6Slide 45 Representing A Table As A 2-Dimensional Array The first dimension or row identifier is Year The second dimension or column identifier is Percentage Any cell contains a balance for a year and a percentage rate Example: the balance for year 4 and rate of 7.00% = $1311 Note: the table assumes a starting balance of $1000

S.Horton/107/Ch. 6Slide 46 Previous Table As A 2-D Java Array Generalize structure to two indexes: [row][column] Each cell contains balance for a year i (row) and a percentage rate j (column) All indexes use zero-numbering. Hence: table[3][4] = cell in 4th row (year = 4) and 5th column (7.50%) table[3][4] = $1311 (shown in yellow) Chapter 11 Row Index 3 (4th row) Column Index 4 (5th column)

S.Horton/107/Ch. 6Slide 47 Generalized syntax for an array is: Base_Type[]…[] Array_Name = new Base_Type[Length_1]…[Length_n]; For example, to declare a 2-D array of float named table from the previous example: float[][] table = new float[5][6]; You can also break-up the declaration as: float[][] table; Definition table = new float[5][]; table[0] = new table[6]; table[1] = new table[6]; table[2] = new table[6]; table[3] = new table[6]; table[4] = new table[6]; Java Syntax to Create Multi-Dimensional Arrays Allocation

S.Horton/107/Ch. 6Slide 48 Processing a 2-D Array: Nested for Loops Arrays and for loops are a natural fit To process all elements of an n -D array, nest n for loops Each loop has its own counter that corresponds to an index For example: populate a 5x6 matrix with values from 1 to 30 The “inner” loop repeats 6 times for every “outer” loop iteration The “outer” loop repeats 5 times The total repeats 6 x 5 = 30 times = # of cells in table int[][] table = new int[5][6]; int row, column, index=0; for (row = 0; row < 5; row++) for (column = 0; column < 6; column++) { index++; table[row][column] = index; }

S.Horton/107/Ch. 6Slide 49 Implementation of Multi-Dimensional Arrays Multi-dimensional arrays are implemented as arrays of arrays. Example: int[][] table = new int[3][4]; table is actually a one-dimensional array of length 3 Each element in table is an array of int with length 4 This is called “row-oriented storage”. Why is this important? To sequentially access elements of a matrix (fastest), you need to loop through the outer most index in the inner most loop table[0] refers to the first row in the array, which is a one-dimensional array itself.

S.Horton/107/Ch. 6Slide 50 Accessing Multi- Dimensional Arrays The.length variable is valid for multi-dimensional arrays, but be careful! table.length is the number of rows of the array table[i].length is the length of the i th row (column length)  Note: drop the outermost index in syntax Example for table below: table.length gives length (3) for the number of rows in the array table[0].length gives length (4) for the length of the row (# of columns) Can the number of columns ever vary or is table[i].length always the same? table[0].length refers to the length of the first row in the array

S.Horton/107/Ch. 6Slide 51 Ragged Arrays Ragged arrays have rows of unequal length. This is allowed in Java! This means that you can never assume that a table or other multi-dimensional array have equal column lengths. There is no special syntax, it is all in the allocation. When is this handy? Think arrays of strings. Example: create a 2-D String array named book with 3 entries. The first entry has length 32, the second row has length 64, and the third row has length 128: String[][] book; book = new String[3][]; book[0] = new String[32]; book[1] = new String[64]; book[2] = new String[128];

S.Horton/107/Ch. 6Slide 52 Multi-Dimensional Arrays As Parameters And Returned Values In Methods Methods may use, pass, and return multi- dimensional array parameters! The situation is similar to 1-D arrays, but with more brackets. You can even pass and return parts of a multi- dimensional array (think individual rows).

S.Horton/107/Ch. 6Slide 53 … /********************************************* * Method to output a table to the console. *********************************************/ public static void displayTable(int[][] A) { int row, col; for (row = 0; row < A.length; row++) { for (col = 0; col < A[row].length; col++) System.out.print(A[row][column] + "\t"); System.out.println(); } Example: Multi-Dimensional Array Parameter

S.Horton/107/Ch. 6Slide 54 … /********************************************************************* * Method to calculate compounded value. The interest rate is in * decimal. Example 5% would be 0.05 *********************************************************************/ public static float balance(float startBalance, int years, float rate) { return startBalance*Math.pow(1.0+rate,(float)years); } Example: Multi-Dimensional Array Parameter

S.Horton/107/Ch. 6Slide 55 Putting It All Together: Calculate Compounding Table From Previous Example Each array element in the table corresponds to the balance for a specific number of years and a specific interest rate (assuming a starting balance of $1000): The formula for computing the ending balance is: endb(startb, years, rate) = (startb) x (1 + rate) years Let’s put this calculation in a nice helper method … /********************************************************************* * Method to calculate compounded value. The interest rate is in * decimal. Example 5% would be 0.05 *********************************************************************/ public static float balance(float startBalance, int years, float rate) { return startBalance*Math.pow(1.0+rate,(float)years); }

S.Horton/107/Ch. 6Slide 56 Pseudocode For Compounding Table 1. Define the table array 2. Loop through each element in table 1. Initialize starting balance to $ Compute ending balance with compound formula 3. Update table element 3. Display the table to the user

S.Horton/107/Ch. 6Slide 57 … float[][] table = new float[5][6]; //Compound table float rate; int row, col, year; for (row=0; row<table.length; row++) for (col=0; col<table[row].length; col++) { year = row + 1;//For years 1-5 rate = ( *col)/100.0; //Rate from 5% - 7.5% table[row][col] = balance(1000.0,year,rate); } displayTable(table); //Show user result Compounding Table Code