Outline. 7.1 Introduction. 7.2 Arrays. 7.2 Arrays

Similar documents
Arrays Introduction. Group of contiguous memory locations. Each memory location has same name Each memory location has same type

Arrays (Deitel chapter 7)

Chapter 6 Arrays and Strings Prentice Hall, Inc. All rights reserved.

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

C Arrays Pearson Education, Inc. All rights reserved.

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd

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

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

Chapter 6 SINGLE-DIMENSIONAL ARRAYS

Chapter 5 - Methods Prentice Hall, Inc. All rights reserved.

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections

Chapter 6 - Methods Prentice Hall. All rights reserved.

Instructor: Eng.Omar Al-Nahal

C++ PROGRAMMING SKILLS Part 4: Arrays

Arrays Data structures Related data items of same type Remain same size once created Fixed-length entries

Part 8 Methods. scope of declarations method overriding method overloading recursions

CS 106 Introduction to Computer Science I

Fundamentals of Programming Session 14

Methods (Deitel chapter 6)

C Arrays. O b j e c t i v e s In this chapter, you ll:

Methods (Deitel chapter 6)

For searching and sorting algorithms, this is particularly dependent on the number of data elements.

Lecture 04 FUNCTIONS AND ARRAYS

C: How to Program. Week /Apr/23

Objectives of This Chapter

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips

Programming for Engineers Arrays

Deitel Series Page How To Program Series

The first applet we shall build will ask the user how many times the die is to be tossed. The request is made by utilizing a JoptionPane input form:

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

Chapter 6. Arrays. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Function Call Stack and Activation Records

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

Arrays. Week 4. Assylbek Jumagaliyev

CSE101-lec#19. Array searching and sorting techniques. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

Multiple-Subscripted Arrays

Assignment Checklist. Prelab Activities. Lab Exercises. Labs Provided by Instructor. Postlab Activities. Section:

Arrays Pearson Education, Inc. All rights reserved.

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

Computer Programming Lecture 14 Arrays (Part 2)

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

C/C++ Programming Lecture 18 Name:

Control Statements. Musa M. Ameen Computer Engineering Dept.

Chapter 5: Enhancing Classes

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

References. Chapter 5: Enhancing Classes. Enhancing Classes. The null Reference. Java Software Solutions for AP* Computer Science A 2nd Edition

Object Oriented Programming. Java-Lecture 6 - Arrays

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

Chapter 9 Introduction to Arrays. Fundamentals of Java

Chapter 7 : Arrays (pp )

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

19 Much that I bound, I could not free; Much that I freed returned to me. Lee Wilson Dodd

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

142

egrapher Language Reference Manual

APCS Semester #1 Final Exam Practice Problems

PLD Semester Exam Study Guide Dec. 2018

8/2/10. Looking for something COMP 10 EXPLORING COMPUTER SCIENCE. Where is the book Modern Interiors? Lecture 7 Searching and Sorting TODAY'S OUTLINE

Outline Introduction Arrays Declaring Arrays Examples Using Arrays Passing Arrays to Functions Sorting Arrays

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Chapter 4 Control Structures: Part 2

by Pearson Education, Inc. All Rights Reserved. 2

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Course PJL. Arithmetic Operations

Chapter 4 Defining Classes I

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

In this chapter you ll learn:

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

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

Chapter 7 Array. Array. C++, How to Program

Contents Chapter 1 Introduction to Programming and the Java Language

Lesson 12: Recursion, Complexity, Searching and Sorting. Modifications By Mr. Dave Clausen Updated for Java 1_5

GUI Forms and Events, Part II

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

C: How to Program. Week /Apr/16

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

CS112 Lecture: Repetition Statements

C Functions. 5.2 Program Modules in C

CHAPTER 4 FUNCTIONS. 4.1 Introduction

STUDENT LESSON A12 Iterations

Control Statements: Part 1

Arrays. Outline. Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Prentice Hall, Inc. All rights reserved.

Full file at

Sorting Algorithms. Array Data is being arranged in ascending order using the bubble sort algorithm. #1 #2 #3 #4 #5 #6 #7

2.8. Decision Making: Equality and Relational Operators

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

Class 27: Nested Classes and an Introduction to Trees

4.1 COMPUTATIONAL THINKING AND PROBLEM-SOLVING

ARRAYS, RECURSION, AND COMPLEXITY

DEMYSTIFYING PROGRAMMING: CHAPTER SIX METHODS (TOC DETAILED) CHAPTER SIX: METHODS 1

Arrays and Applications

Chapter 3: Operators, Expressions and Type Conversion

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

Transcription:

jhtp5_07.fm Page 279 Wednesday, November 20, 2002 12:44 PM 7 Arrays Objectives To introduce the array data structure. To understand the use of arrays to store, sort and search lists and tables of values. To understand how to declare an array, initialize an array and refer to individual elements of an array. To be able to pass arrays to methods. To be able to declare and manipulate multidimensional arrays. With sobs and tears he sorted out Those of the largest size Lewis Carroll Attempt the end, and never stand to doubt; Nothing s so hard, but search will find it out. Robert Herrick Now go, write it before them in a table, and note it in a book. Isaiah 30:8 Tis in my memory lock d, And you yourself shall keep the key of it. William Shakespeare

280 Arrays Chapter 7 Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Creating Arrays 7.4 Examples Using Arrays 7.5 References and Reference Parameters 7.6 Passing Arrays to Methods 7.7 Sorting Arrays 7.8 Searching Arrays: Linear Search and Binary Search 7.9 Multidimensional Arrays 7.10 (Optional Case Study) Thinking About Objects: Collaboration Among Objects Summary Terminology Self-Review Exercises Answers to Self-Review Exercises Exercises Recursion Exercises Special Section: Building Your Own Computer 7.1 Introduction This chapter introduces the important topic of data structures collections of related data items. Arrays are data structures consisting of related data items of the same type. Arrays are fixed-length entities they remain the same length once they are created, although an array reference may be reassigned to a new array of a different length. Chapter 20, Data Structures, introduces dynamic data structures, such as lists, queues, stacks and trees, that can grow and shrink as programs execute. Chapter 21, Java Utilities Package and Bit Manipulation, discusses class Vector, which is an array-like class whose objects can grow and shrink in response to a Java program s changing storage requirements. Chapter 22, Collections, introduces Java s predefined data structures that enable the programmer to use existing data structures for lists, queues, stacks and trees. The Collections API also provides class Arrays, which provides a set of utility methods for array manipulation. 7.2 Arrays In Java, an array is a group of variables (called elements or components) containing values that all have the same type. Recall from Section 3.5 that types in Java are divided into two categories primitive types and reference types. Java arrays are objects, so they are considered reference types. The elements of a Java array can be either primitive types or reference types (including arrays, as we will see in Section 7.9). To refer to a particular element in an array, we specify the name of the reference to the array and the position number of the element in the array. The position number of the element is formally called the element s index or subscript. Figure 7.1 presents a logical representation of an integer array called c. This array contains 12 elements (i.e., variables). A program refers to any one of these elements with an array-access expression that includes the name of the array followed by the index of the particular element in square brackets ( []). The first element in every array has index zero

Chapter 7 Arrays 281 Name of array (note that all elements of this array have the same name, c ) Index (or subscript) of the element in array c c[ 0 ] c[ 1 ] c[ 2 ] c[ 3 ] c[ 4 ] c[ 5 ] c[ 6 ] c[ 7 ] c[ 8 ] c[ 9 ] c[ 10 ] c[ 11 ] -45 6 0 72 1543-89 0 62-3 1 6453 78 Fig. 7.1 A 12-element array. (sometimes called the zeroth element). Thus, the first element of array c is c[ 0], the second element of array c is c[ 1], the seventh element of array c is c[ 6] and, in general, the i th element of array c is c[ i-1]. Array names follow the same conventions as do other variable names. An index must be a positive integer or an integer expression that can be promoted to an int. If a program uses an expression as an index, the program evaluates the expression to determine the index. For example, if we assume that variable a is 5 and that variable b is 6, then the statement c[ a + b ] += 2 ; adds 2 to array element c[ 11 ]. Note that an indexed array name is an array-access expression. Such expressions can be used on the left side of an assignment to place a new value into an array element. Common Programming Error 7.1 Using a value of type long as an array index results in a compilation error. 7.1 Let us examine array c in Fig. 7.1 more closely. The name of the reference to the array is c. Every array object in Java knows its own length and maintains this information in a field of the array object called length. The expression c.length accesses array c s length field to determine the length of the array. This array s 12 elements are referred to as c[ 0], c[ 1], c[ 2],, c[ 11 ]. The value of c[ 0] is -45, the value of c[ 1] is 6, the value of c[ 2] is 0, the value of c[ 7] is 62 and the value of c[ 11 ] is 78. To calculate the sum

282 Arrays Chapter 7 of the values contained in the first three elements of array c and store the result in variable sum, we would write sum = c[ 0 ] + c[ 1 ] + c[ 2 ]; To divide the value of the seventh element of array c by 2 and assign the result to the variable x, we would write x = c[ 6 ] / 2 ; Common Programming Error 7.2 Note the difference between the seventh element of the array and array element seven. Array indices begin at 0, so the seventh element of the array has an index of 6, while array element seven has an index of 7 and is actually the eighth element of the array. This confusion is a source of off-by-one errors. 7.2 7.3 Declaring and Creating Arrays Array objects occupy space in memory. All objects in Java (including arrays) must be created with keyword new (as discussed in Section 4.9). For an array, the programmer specifies the type of the array elements and the number of elements as part of an array-creation expression that uses keyword new. The following declaration and array-creation expression create 12 elements for the integer array c in Fig. 7.1: int c[] = new int [ 12 ]; This task also can be performed in two steps as follows: int c[]; // declares the array variable c = new int [ 12 ]; // creates the array When creating an array, each element of the array receives a default value zero for the numeric primitive-type elements, false for boolean elements and null for references (any nonprimitive type). Common Programming Error 7.3 Unlike array declarations in several other programming languages (such as C and C++), Java array declarations do not specify the number of array elements in the square brackets after the array name (e.g., int c[ 12 ] ; ); otherwise, a syntax error occurs. 7.3 A program can create several arrays in a single declaration. The following String array declaration reserves 100 elements for b and 27 elements for x : String b[] = new String[ 100 ], x[] = new String[ 27 ]; When declaring an array, the type of the array and the square brackets can be combined at the beginning of the declaration to indicate that all identifiers in the declaration are array references. For example, double[] array1, array2; declares array1 and array2 as references to arrays of double values. As shown previously, the declaration and creation of the array can be combined in the declaration. The following declaration reserves 10 elements for array1 and 20 elements for array2:

Chapter 7 Arrays 283 double[] array1 = new double[ 10 ], array2 = new double[ 20 ]; A program can declare arrays of any type. Every element of a primitive-type array contains is a variable of the array s declared type. For example, every element of an int array is an int variable. In an array of a reference type, every element of the array is a reference to an object of the array s declared type. For example, every element of a String array is a reference to a String object. 7.4 Examples Using Arrays This section presents several examples that demonstrate declaring arrays, creating arrays, initializing arrays and manipulating array elements. For simplicity, the examples in this section use arrays that contain elements of type int. Please remember that programs can create arrays of any type. Creating and Initializing an Array The application of Fig. 7.2 uses keyword new to create an array of 10 int elements, which are initially zero (the default for int variables). The program displays the array elements in tabular format in an object of class JTextArea. 1 // Fig. 7.2: InitArray.java 2 // Creating an array. 3 import javax.swing.*; 4 5 public class InitArray { 6 7 public static void main( String args[] ) 8 { 9 10 int array[]; // declare reference to an array 11 array = new int [ 10 ]; // create array 12 13 String output = "Index\tValue\n"; 14 15 16 17 18 19 // append each array element's value to String output for ( int counter = 0 ; counter < array.length; counter++ ) output += counter + "\t" + array[ counter ] + "\n"; JTextArea outputarea = new JTextArea(); 20 outputarea.settext( output ); 21 22 JOptionPane.showMessageDialog( null, outputarea, 23 "Initializing an Array of int Values", 24 JOptionPane.INFORMATION_MESSAGE ); 25 26 System.exit( 0 ); 27 28 } // end main 29 30 } // end class InitArray Fig. 7.2 Initializing the elements of an array to zero. (Part 1 of 2.)

284 Arrays Chapter 7 Fig. 7.2 Initializing the elements of an array to zero. (Part 2 of 2.) Line 9 declares array a reference capable of referring to an array of int elements. Line 11 creates the array and assigns a reference to the resulting array object to reference array. The program builds its output in the String called output that will be displayed in a JTextArea on a message dialog. Line 13 assigns output the headings for the columns displayed by the program. The first column represents the index for each array element, and the second column represents the value of each array element. Lines 16 17 use a for statement to append the index number (represented by counter ) and value of each array element (represented by array[ counter ] ) to output. Note that the loop uses zero-based counting (remember, index values start at 0), so that the loop can access every array element. Also, in the for s condition, note the use of the expression array.length to determine the length of the array. In this example, the length of the array is 10, so the loop continues executing as long as the value of control variable counter is less than 10. For a 10-element array, the index values are 0 through 9, so using the less-than operator guarantees that the loop does not attempt to access an element beyond the end of the array. Using an Array Initializer As an alternative to an array-creation expression, a program can create an array and initialize its elements with an array initializer, which is a comma-separated list of expressions (sometimes called an initializer list) enclosed in braces ( { and } ). In this case, the array length is determined by the number of elements in the initializer list. For example, the declaration int n[] = { 10, 20, 30, 40, 50 }; creates a five-element array with index values 0, 1, 2, 3 and 4. This declaration does not require new to create the array object. When the compiler encounters an array declaration that includes an initializer list, the compiler counts the number of initializers in the list to determine the appropriate number of array elements. The application of Fig. 7.3 initializes an integer array with 10 values (line 11) and displays the array in tabular format in a JTextArea on a message dialog. The code for displaying the array elements (lines 13 24) is identical to that of Fig. 7.2.

Chapter 7 Arrays 285 1 // Fig. 7.3: InitArray.java 2 // Initializing an array with a declaration. 3 import javax.swing.*; 4 5 public class InitArray { 6 7 public static void main( String args[] ) 8 { 9 10 11 12 // array initializer specifies number of elements and // value for each element int array[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; 13 String output = "Index\tValue\n"; 14 15 // append each array element's value to String output 16 for ( int counter = 0 ; counter < array.length; counter++ ) 17 output += counter + "\t" + array[ counter ] + "\n"; 18 19 JTextArea outputarea = new JTextArea(); 20 outputarea.settext( output ); 21 22 JOptionPane.showMessageDialog( null, outputarea, 23 "Initializing an Array with a Declaration", 24 JOptionPane.INFORMATION_MESSAGE ); 25 26 System.exit( 0 ); 27 28 } // end main 29 30 } // end class InitArray Fig. 7.3 Initializing the elements of an array with a declaration. Calculating the Value to Store in Each Array Element Some programs calculate the value stored in each array element. The application of Fig. 7.4 creates a 10-element array and assigns each element on of the even integers from 2 to 20 ( 2, 4, 6,, 20). Then the program displays the array in tabular format. The for statement at lines 15 16 generates an array element s value by multiplying the current value of the for loop s control variable counter by 2 and adding 2.

286 Arrays Chapter 7 1 // Fig. 7.4: InitArray.java 2 // Initialize array with the even integers from 2 to 20. 3 import javax.swing.*; 4 5 public class InitArray { 6 7 public static void main( String args[] ) 8 { 9 10 11 final int ARRAY_LENGTH = 10 ; int array[]; // constant // reference to int array 12 array = new int [ ARRAY_LENGTH ]; // create array 13 14 // calculate value for each array element 15 for ( int counter = 0 ; counter < array.length; counter++ ) 16 array[ counter ] = 2 + 2 * counter; 17 18 String output = "Index\tValue\n"; 19 20 for ( int counter = 0 ; counter < array.length; counter++ ) 21 output += counter + "\t" + array[ counter ] + "\n"; 22 23 JTextArea outputarea = new JTextArea(); 24 outputarea.settext( output ); 25 26 JOptionPane.showMessageDialog( null, outputarea, 27 "Initializing to Even Numbers from 2 to 20", 28 JOptionPane.INFORMATION_MESSAGE ); 29 30 System.exit( 0 ); 31 32 } // end main 33 34 } // end class InitArray Fig. 7.4 Generating values to be placed into elements of an array. Line 9 uses the final qualifier to declare constant ARRAY_LENGTH, whose value is 10. Recall from Section 6.8 that constants must be initialized before they are used and

Chapter 7 Arrays 287 cannot be modified thereafter. If an attempt is made to modify a final variable after it is declared as shown on line 11, the compiler issues a message like cannot assign a value to final variable variablename If an attempt is made to use a final variable before it is initialized, the compiler issues the error message Variable variablename may not have been initialized Constants also are called named constants or read-only variables. Such variables often can make programs more readable. Common Programming Error 7.4 Assigning a value to a constant after the variable has been initialized results in a compilation error. 7.4 Summing the Elements of an Array Often, the elements of an array represent a series of values to be used in a calculation. For example, if the elements of an array represent the grades for an exam, the professor may wish to total the elements of the array and use that sum to calculate the class average for the exam. The application of Fig. 7.5 sums the values contained in the 10-element integer array. The program declares, creates and initializes the array at line 9. The for statement at lines 13 14 performs the calculations. [ Note: The values supplied as array initializers normally are read into a program, rather than specified in an initializer list. For example, an applet user could enter the values through a JTextField, or, in an application, the values could be read from a file on disk (as discussed in Chapter 17). Reading the data into a program makes the program more flexible, because it can be used with different sets of data.] 1 // Fig. 7.5: SumArray.java 2 // Total the values of the elements of an array. 3 import javax.swing.*; 4 5 public class SumArray { 6 7 public static void main( String args[] ) 8 { 9 int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 10 int total = 0 ; 11 12 13 14 15 // add each element's value to total for ( int counter = 0 ; counter < array.length; counter++ ) total += array[ counter ]; 16 JOptionPane.showMessageDialog( null, 17 "Total of array elements: " + total, 18 "Sum the Elements of an Array", 19 JOptionPane.INFORMATION_MESSAGE ); 20 Fig. 7.5 Computing the sum of the elements of an array. (Part 1 of 2.)

288 Arrays Chapter 7 21 System.exit( 0 ); 22 23 } // end main 24 25 } // end class SumArray Fig. 7.5 Computing the sum of the elements of an array. (Part 2 of 2.) Using Histograms to Display Array Data Graphically Many programs present data to users in a graphical manner. For example, numeric values are often displayed as bars in a bar chart, or histogram. In such a chart, longer bars represent larger numeric values. One simple way to display numeric data graphically is with a histogram that shows each numeric value as a bar of asterisks ( * ). Our next application (Fig. 7.6) reads numbers from an array and graphs the information in the form of a histogram. The program displays each value followed by a bar consisting of that many asterisks. The nested for statements (lines 14 21) append the bars to the string output that will be displayed in textarea outputarea on a message dialog. Note the condition of the for statement at line 18 (stars <array[ counter ] ). Each time the program reaches that inner for statement (lines 18 19), the loop counts from 0 up to array[counter], thus using a value in array to determine the final value of the control variable stars and the number of asterisks to display. 1 // Fig. 7.6: Histogram.java 2 // Histogram printing program. 3 import javax.swing.*; 4 5 public class Histogram { 6 7 public static void main( String args[] ) 8 { 9 int array[] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; 10 11 String output = "Element\tValue\tHistogram"; 12 13 // for each array element, output a bar in histogram 14 for ( int counter = 0 ; counter < array.length; counter++ ) { 15 16 17 18 19 20 21 } // end outer for output += "\n" + counter + "\t" + array[ counter ] + "\t" ; // print bar of asterisks for ( int stars = 0 ; stars < array[ counter ]; stars++ ) output += "*" ; Fig. 7.6 A program that prints histograms. (Part 1 of 2.)

Chapter 7 Arrays 289 22 23 JTextArea outputarea = new JTextArea(); 24 outputarea.settext( output ); 25 26 JOptionPane.showMessageDialog( null, outputarea, 27 "Histogram Printing Program", JOptionPane.INFORMATION_MESSAGE ); 28 29 System.exit( 0 ); 30 31 } // end main 32 33 } // end class Histogram Fig. 7.6 A program that prints histograms. (Part 2 of 2.) Using the Elements of an Array as Counters Sometimes, programs use a series of counter variables to summarize data, such as the results of a survey. In Fig. 6.8, we used a series of counters in our die-rolling program to track the number of occurrences of each side on a six-sided die as the program rolled the die 6000 times. We also indicated that there is a more elegant technique for summarizing the die values. An array version of the application in Fig. 6.8 is shown in Fig. 7.7. 1 // Fig. 7.7: RollDie.java 2 // Roll a six-sided die 6000 times. 3 import javax.swing.*; 4 5 public class RollDie { 6 7 public static void main( String args[] ) 8 { 9 int frequency[] = new int [ 7 ]; 10 11 // roll die 6000 times; use die value as frequency index 12 for ( int roll = 1 ; roll <= 6000; roll++ ) 13 14 15 ++frequency[ 1 + ( int ) ( Math.random() * 6 ) ]; String output = "Face\tFrequency"; 16 Fig. 7.7 Die-rolling program using arrays instead of switch. (Part 1 of 2.)

290 Arrays Chapter 7 17 // append frequencies to String output 18 for ( int face = 1 ; face < frequency.length; face++ ) 19 output += "\n" + face + "\t" + frequency[ face ]; 20 21 JTextArea outputarea = new JTextArea(); 22 outputarea.settext( output ); 23 24 JOptionPane.showMessageDialog( null, outputarea, 25 "Rolling a Die 6000 Times", JOptionPane.INFORMATION_MESSAGE ); 26 27 System.exit( 0 ); 28 29 } // end main 30 31 } // end class RollDie Fig. 7.7 Die-rolling program using arrays instead of switch. (Part 2 of 2.) The program uses the seven-element array frequency (line 9) to count the occurrences of each side of the die. Line 13 of this program replaces lines 17 43 of Fig. 6.8. Line 13 uses the random value as the index for array frequency to determine which element the program should increment during each iteration of the loop. The random-number calculation on line 13 produces numbers from 1 to 6 (the values for a six-sided die), so the frequency array must be large enough to store six counters. However, in this program, we chose to use a seven-element array. We ignore the first array element, frequency[ 0], because it is more logical to have the face value 1 increment frequency[ 1] than frequency[ 0]. This allows us to use each face value directly as an index for array frequency. Good Programming Practice 7.1 Strive for program clarity. It is sometimes worthwhile to trade off the most efficient use of memory or processor time in favor of writing clearer programs. 7.1 Also, lines 18 19 of this program replace lines 49 52 from Fig. 6.8. We can loop through array frequency, so we do not have to enumerate each line of text to display in the JTextArea as we did in Fig. 6.8. Using Arrays to Analyze Survey Results Our next example uses arrays to summarize the results of data collected in a survey. Consider the following problem: Forty students were asked to rate the quality of the food in the student cafeteria on a scale of 1 to 10 (where 1 means awful and 10 means excellent). Place the 40 responses in an integer array, and summarize the results of the poll.

Chapter 7 Arrays 291 The solution to this problem is a typical array-processing application (see Fig. 7.8). We wish to summarize the number of responses of each type (i.e., 1 through 10). The array responses is a 40-element integer array of the students responses to the survey. We use an 11-element array frequency to count the number of occurrences of each response. As in Fig. 7.7, we ignore the first element ( frequency[ 0] ), because it is more logical to have the response 1 increment frequency[ 1] than frequency[ 0]. This allows us to use each response directly as the frequency array index. Each element of the array is used as a counter for one of the survey responses. The for loop at lines 16 17 takes the responses one at a time from array responses and increments one of the 10 counters in the frequency array ( frequency[ 1] to frequency[ 10 ] ). The key statement in the loop is line 17, which increments the appropriate frequency counter, depending on the value of responses[ answer ]. 1 // Fig. 7.8: StudentPoll.java 2 // Student poll program. 3 import javax.swing.*; 4 5 public class StudentPoll { 6 7 public static void main( String args[] ) 8 { 9 int responses[] = { 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6, 10 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6, 11 4, 8, 6, 8, 10 }; 12 13 14 // for each answer, select responses element and use that value 15 // as frequency index to determine element to increment 16 for ( int answer = 0 ; answer < responses.length; answer++ ) 17 18 int frequency[] = new int [ 11 ]; ++frequency[ responses[ answer ] ]; 19 String output = "Rating\tFrequency\n"; 20 21 // append frequencies to String output 22 for ( int rating = 1 ; rating < frequency.length; rating++ ) 23 output += rating + "\t" + frequency[ rating ] + "\n"; 24 25 JTextArea outputarea = new JTextArea(); 26 outputarea.settext( output ); 27 28 JOptionPane.showMessageDialog( null, outputarea, 29 "Student Poll Program", JOptionPane.INFORMATION_MESSAGE ); 30 31 System.exit( 0 ); 32 33 } // end main 34 35 } // end class StudentPoll Fig. 7.8 A simple student-poll analysis program. (Part 1 of 2.)

292 Arrays Chapter 7 Fig. 7.8 A simple student-poll analysis program. (Part 2 of 2.) Let s consider several iterations of the for loop. When control variable answer is 0, the value of responses[ answer ] is the value of the first element of array responses (i.e., 1 ), so the program interprets ++frequency[ responses[ answer ]]; as ++frequency[ 1 ]; which increments the value in array element one. To evaluate the expression, start with the value in the innermost set of square brackets (answer ). Once you know answer s value, plug that value into the expression and evaluate the next outer set of square brackets (i.e., responses[answer] ). Then, use the resulting value as the index for the frequency array to determine which counter to increment. When answer is 1, responses[ answer ] is the value of responses s second element ( 2 ), so the program interprets ++frequency[ responses[ answer ]]; as ++frequency[ 2 ]; which increments array element two (the third element of the array). When answer is 2, responses[ answer ] is the value of responses s third element ( 6 ), so the program interprets ++frequency[ responses[ answer ]]; as ++frequency[ 6 ]; which increments array element six (the seventh element of the array), and so on. Regardless of the number of responses processed in the survey, the program requires only an 11- element array (ignoring element zero) to summarize the results, because all the response values are between 1 and 10 and the index values for an 11-element array are 0 through 10. Also, note that the summarized results are correct, because the elements of array frequency were initialized to zero when the array was created with new. If the data had contained invalid values, such as 13, the program would have attempted to add 1 to frequency[13]. This element is outside the bounds of the array. In the C and C++ programming languages, such a reference would be allowed by the compiler and at execution time. The program would walk past the end of the array to where element number 13 would have been located had it existed and add 1 to whatever happens to be at that location in memory. This operation could potentially modify another variable in the

Chapter 7 Arrays 293 program or even result in premature program termination. Java prevents accessing elements outside the array bounds. Error-Prevention Tip 7.1 When a Java program executes, the Java interpreter checks array indices to ensure that they are valid (i.e., all array indices must be greater than or equal to 0 and less than the length of the array). If there is an invalid index, Java generates an exception. 7.1 Error-Prevention Tip 7.2 Exceptions indicate that an error occurred in a program. A programmer can write code to recover from an exception and continue program execution, rather than abnormally terminating the program. When a program attempts to access an element outside the array bounds, Java generates an ArrayIndexOutOfBoundsException. 1 7.2 Error-Prevention Tip 7.3 When looping through an array, the array index should never go below 0 and should always be less than the length of the array. The loop-terminating condition should prevent the accessing of elements outside this range. 7.3 7.5 References and Reference Parameters Section 7.5 demonstrates how to pass arrays and array elements as arguments to methods. First, we introduce the mechanisms used to pass arguments to methods. Two ways to pass arguments to methods in many programming languages (like C and C++) are pass-by-value and pass-by-reference (also called call-by-value and call-by-reference ). When an argument is passed by value, a copy of the argument s value is made and passed to the called method. Error-Prevention Tip 7.4 With pass-by-value, changes to the called method s copy do not affect the original variable s value in the caller. This prevents the accidental side effects that greatly hinder the development of correct and reliable software systems. 7.4 When an argument is passed by reference, the caller gives the called method the ability to access the caller s data directly and possibly modify that data. Pass-by-reference also improves performance by eliminating the overhead of copying large amounts of data. Software Engineering Observation 7.1 Unlike other languages, Java does not allow the programmer to choose whether to pass each argument by value or by reference. Primitive-type variables are always passed by value. Objects are not passed to methods; rather, references to objects are passed. The references themselves are passed by value that is, a copy of a reference is passed to a method. With a reference to an object, the method can manipulate the object directly. 7.1 Software Engineering Observation 7.2 When returning information from a method via a return statement, primitive types are always returned by value (i.e., a copy is returned) and objects are always returned by reference (i.e., a reference to the object is returned). 7.2 1. Exception handling is discussed in Chapter 15.

294 Arrays Chapter 7 To pass a reference to an object to a method, simply specify the reference name in the method call. The corresponding method-parameter name actually refers to the original object in memory, and the original object can thus be accessed directly in the called method. Recall from Section 7.2 that arrays are objects in Java; therefore, arrays are passed to methods by reference a called method can access the elements of the caller s original arrays. The name of an array variable is actually a reference to an object that contains the array elements and the length field, a constant that indicates the number of elements in the array. In the next section, we demonstrate pass-by-value and pass-by-reference as used with arrays. Performance Tip 7.1 Passing arrays by reference makes sense for performance reasons. If arrays were passed by value, a copy of each element would be passed. For large, frequently passed arrays, this would waste time and would consume a considerable amount of storage for the copies of the arrays. 7.1 7.6 Passing Arrays to Methods To pass an array argument to a method, specify the name of the array without any brackets. For example, if array hourlytemperatures is declared as int hourlytemperatures[] = new int [ 24 ]; then the method call modifyarray( hourlytemperatures ); passes a reference to array hourlytemperatures to method modifyarray. In Java, every array object knows its own length (via the length field). Thus, when we pass an array object into a method, we are not required to pass the length of the array as an additional argument. Although entire arrays and objects referred to by individual elements of reference-type arrays are passed by reference, individual array elements of primitive types are passed by value exactly as simple variables are. Such primitive values are called scalars or scalar quantities. To pass an array element to a method, use the indexed name of the array as an argument in the method call. For a method to receive an array through a method call, the method s parameter list must specify an array parameter (or several if more than one array is to be received). For example, the method header for method modifyarray might be written as void modifyarray( int b[] ) indicating that modifyarray expects to receive an integer array in parameter b. Since arrays are passed by reference, when the called method uses the array name b, it refers to the actual array ( hourlytemperatures in the preceding call) in the calling method. The applet of Fig. 7.9 demonstrates the difference between passing an entire array and passing a primitive-type array element. Once again, we use an applet here because we have not yet defined an application that contains methods other than main. We are still taking advantage of some applet features, such as the automatic creation of an applet object and

Chapter 7 Arrays 295 the calls to init, start and paint by the applet container. In Chapter 9, Object-Oriented Programming, we will introduce applications that execute in their own windows. At that point, we will begin to see application classes that contain several methods. 1 // Fig. 7.9: PassArray.java 2 // Passing arrays and individual array elements to methods. 3 import java.awt.container; 4 import javax.swing.*; 5 6 public class PassArray extends JApplet { 7 8 // initialize applet 9 public void init() 10 { 11 JTextArea outputarea = new JTextArea(); 12 Container container = getcontentpane(); 13 container.add( outputarea ); 14 15 int array[] = { 1, 2, 3, 4, 5 }; 16 17 String output = "Effects of passing entire array by reference:\n" + 18 "The values of the original array are:\n"; 19 20 // append original array elements to String output 21 for ( int counter = 0 ; counter < array.length; counter++ ) 22 output += " " + array[ counter ]; 23 24 25 26 output += "\n\nthe values of the modified array are:\n"; 27 28 // append modified array elements to String output 29 for ( int counter = 0 ; counter < array.length; counter++ ) 30 output += " " + array[ counter ]; 31 32 output += "\n\neffects of passing array element by value:\n" + 33 "array[3] before modifyelement: " + array[ 3 ]; 34 35 modifyelement( array[ 3 ] ); // attempt to modify array[ 3 ] 36 37 output += "\narray[3] after modifyelement: " + array[ 3 ]; 38 outputarea.settext( output ); 39 40 } // end method init 41 42 43 44 45 46 47 48 modifyarray( array ); // array passed by reference // multiply each element of an array by 2 public void modifyarray( int array2[] ) { for ( int counter = 0 ; counter < array2.length; counter++ ) array2[ counter ] *= 2 ; } Fig. 7.9 Passing arrays and individual array elements to methods. (Part 1 of 2.)

296 Arrays Chapter 7 49 // multiply argument by 2 50 public void modifyelement( int element ) 51 { 52 element *= 2 ; 53 } 54 55 } // end class PassArray Fig. 7.9 Passing arrays and individual array elements to methods. (Part 2 of 2.) Lines 11 13 in method init create the JTextArea called outputarea and attach it to the applet s content pane. The for statement at lines 21 22 appends the five elements of array (an array of int values) to the String called output. Line 24 invokes method modifyarray, passing array as an argument. Method modifyarray (lines 43 47) multiplies each element by two. To illustrate that array s elements were modified, the for statement at lines 29 30 appends the five elements of array to output again. As the screen capture shows, method modifyarray did change the value of each element. Next, the program demonstrates that individual elements of primitive-type arrays are passed to methods by value. To show the value of array[ 3] before calling method modifyelement, lines 32 33 append the value of array[ 3] (the fourth element with the value 8) to output. Line 35 invokes method modifyelement and passes array[ 3] as an argument. Remember that array[ 3] is actually one int value (8) in array. Also, remember that values of primitive types are passed to methods by value. Therefore, the program passes a copy of array[ 3]. Method modifyelement multiplies its argument by two and stores the result (16) in its parameter element. Method parameters, like local variables, cease to exist when the method in which they are declared completes execution. So, when method modifyelement terminates, the method parameter element is destroyed. Thus, when the program returns control to init, line 37 appends the unmodified value of array[ 3] (i.e., 8) to output. Line 38 displays the results in the JTextArea. 7.7 Sorting Arrays Sorting data (i.e., placing the data into some particular order, such as ascending or descending) is one of the most important computing applications. A bank sorts all checks by account number so that it can prepare individual bank statements at the end of each month. Telephone companies sort their lists of accounts by last name and, further, by first name to make it easy to find phone numbers. Virtually every organization must sort some data and, in many cases, massive amounts of data. Sorting data is an intriguing problem that has at-

Chapter 7 Arrays 297 tracted some of the most intense research efforts in the field of computer science. In this chapter, we discuss one of the simplest sorting schemes. In the exercises in this chapter, Chapter 20 and Chapter 22, we investigate more complex schemes that yield superior performance. Figure 7.10 sorts the values of array (a 10-element array of int variables) into ascending order. The technique we use is called the bubble sort or the sinking sort, because the smaller values gradually bubble their way to the top of the array (i.e., toward the first element) like air bubbles rising in water, while the larger values sink to the bottom (end) of the array. The technique uses nested loops to make several passes through the array. Each pass compares successive pairs of elements. If a pair is in increasing order (or the values are equal), the bubble sort leaves the values as they are. If a pair is in decreasing order, the bubble sort swaps their values in the array. The applet contains methods init, bubble- Sort and swap. Method init (lines 9 33) initializes the applet. Method bubblesort (lines 36 55) is called from init to sort the elements of array. Method bubblesort calls method swap (lines 58 65) as necessary to exchange two elements of the array. 1 // Fig. 7.10: BubbleSort.java 2 // Sort an array's values into ascending order. 3 import java.awt.*; 4 import javax.swing.*; 5 6 public class BubbleSort extends JApplet { 7 8 // initialize applet 9 public void init() 10 { 11 JTextArea outputarea = new JTextArea(); 12 Container container = getcontentpane(); 13 container.add( outputarea ); 14 15 int array[] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; 16 17 String output = "Data items in original order\n"; 18 19 // append original array values to String output 20 for ( int counter = 0 ; counter < array.length; counter++ ) 21 output += " " + array[ counter ]; 22 23 24 bubblesort( array ); // sort array 25 output += "\n\ndata items in ascending order\n"; 26 27 // append sorted\ array values to String output 28 for ( int counter = 0 ; counter < array.length; counter++ ) 29 output += " " + array[ counter ]; 30 31 outputarea.settext( output ); 32 33 } // end method init 34 Fig. 7.10 Sorting an array with bubble sort. (Part 1 of 2.)

298 Arrays Chapter 7 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 } // end method bubblesort 56 57 58 59 60 61 62 63 64 65 } 66 67 } // end class BubbleSort // sort elements of array with bubble sort public void bubblesort( int array2[] ) { // loop to control number of passes for ( int pass = 1 ; pass < array2.length; pass++ ) { // loop to control number of comparisons for ( int element = 0 ; element < array2.length - 1 ; element++ ) { // compare side-by-side elements and swap them if // first element is greater than second element if ( array2[ element ] > array2[ element + 1 ] ) swap( array2, element, element + 1 ); } // end loop to control comparisons } // end loop to control passes // swap two elements of an array public void swap( int array3[], int first, int second ) { int hold; // temporary holding area for swap hold = array3[ first ]; array3[ first ] = array3[ second ]; array3[ second ] = hold; Fig. 7.10 Sorting an array with bubble sort. (Part 2 of 2.) Lines 20 21 append the original values of array to the String called output. Line 23 invokes method bubblesort and passes array as the array to sort. The method receives the array as parameter array2. The nested for statement at lines 39 53 performs the sort. The outer loop controls the number of passes of the array. The inner loop controls the comparisons and swapping (if necessary) of the elements during each pass. Method bubblesort compares array2[ 0] to array2[ 1], then array2[ 1] to array2[ 2], then array2[ 2] to array2[ 3] and so on until it completes the pass by comparing array2[ 8] to array2[ 9]. Although there are 10 elements, the comparison loop per-

Chapter 7 Arrays 299 forms only nine comparisons. During each pass, a large value might move down the array (sink) many positions. However, a small value can move up (bubble) only one position per pass. On the first pass, the largest value is guaranteed to sink to the bottom element of the array, array2[ 9]. On the second pass, the second largest value is guaranteed to sink to array2[ 8]. On the ninth pass, the ninth largest value sinks to array2[ 1], leaving the smallest value in array2[ 0]. So, only nine passes are required to sort a 10-element array. If a comparison reveals that the two elements are in descending order, line 49 of bubblesort calls method swap to exchange the two elements so they will be in ascending order in the array. Method swap receives a reference to the array (which it calls array3) and two integers representing the indices of the two elements of the array to exchange. The exchange is performed by the three assignments in lines 62 64. The extra variable hold temporarily stores one of the two values being swapped. The swap cannot be performed with only the two assignments array3[ first ] = array3[ second ]; array3[ second ] = array3[ first ]; If array3[ first ] is 7 and array3[ second ] is 5, after the first assignment both array elements contain 5 and the value 7 is lost hence, the extra variable hold is needed. The chief virtue of the bubble sort is that it is easy to program. However, the bubble sort runs slowly. This becomes apparent when sorting large arrays. In Exercise 7.11, we ask you to develop more efficient versions of the bubble sort. Other exercises investigate some sorting algorithms that are far more efficient than the bubble sort. 2 Performance Tip 7.2 Sometimes, the simplest algorithms perform poorly. Their virtue is that they are easy to program, test and debug. Sometimes, more complex algorithms are required to realize maximum performance. 7.2 7.8 Searching Arrays: Linear Search and Binary Search Often, programmers work with large amounts of data stored in arrays. It may be necessary to determine whether an array contains a value that matches a certain key value. The process of locating a key value in an array is called searching. In this section, we discuss two searching techniques the simple linear search and the more efficient binary search. 3 Searching an Array with Linear Search In the applet of Fig. 7.11, method linearsearch (declared at lines 47 58) uses a for statement (lines 50 54) containing an if statement to iterate over the elements of an array and compare each element with a search key the value to locate in the array. If the search key is found, the method returns the index of the element, thereby indicating the exact position of the search key in the array. If the search key is not found, the method returns the value 1. We return 1 because it is not a valid index. If the array being searched is not in any particular order, it is just as likely that the search key will be found in the first element 2. More advanced courses (often titled Data Structures, Algorithms or Computational Complexity ) investigate sorting and searching in greater depth. 3. Exercise 7.33 and Exercise 7.34 ask you to implement recursive versions of the linear search and the binary search, respectively.

300 Arrays Chapter 7 as the last. On average, therefore, the program will have to compare the search key with half the elements of the array. Figure 7.11 contains a 100-element array filled with the even integers from 0 to 198. The user types the search key in a JTextField and presses Enter to start the search. We pass a reference to the array to method linearsearch even though the array can be accessed in that method directly via the field array of class LinearSearch. We do this because a reference to an array normally is passed to a method of another class to search the corresponding array. For example, class Arrays (see Chapter 22) contains a variety of static methods for sorting arrays; searching arrays; comparing the contents of arrays; and filling arrays of primitive types, arrays of Object s and arrays of Strings. 1 // Fig. 7.11: LinearSearch.java 2 // Linear search of an array. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class LinearSearch extends JApplet implements ActionListener { 8 9 JLabel enterlabel, resultlabel; 10 JTextField enterfield, resultfield; 11 int array[]; 12 13 // set up applet's GUI 14 public void init() 15 { 16 // get content pane and set its layout to FlowLayout 17 Container container = getcontentpane(); 18 container.setlayout( new FlowLayout() ); 19 20 // set up JLabel and JTextField for user input 21 enterlabel = new JLabel( "Enter integer search key" ); 22 container.add( enterlabel ); 23 24 enterfield = new JTextField( 10 ); 25 container.add( enterfield ); 26 27 // register this applet as enterfield's action listener 28 enterfield.addactionlistener( this ); 29 30 // set up JLabel and JTextField for displaying results 31 resultlabel = new JLabel( "Result" ); 32 container.add( resultlabel ); 33 34 resultfield = new JTextField( 20 ); 35 resultfield.seteditable( false ); 36 container.add( resultfield ); 37 38 // create array and populate with even integers 0 to 198 39 array = new int [ 100 ]; 40 Fig. 7.11 Linear search of an array. (Part 1 of 2.)

Chapter 7 Arrays 301 41 for ( int counter = 0 ; counter < array.length; counter++ ) 42 array[ counter ] = 2 * counter; 43 44 } // end method init 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 // search array for specified key value public int linearsearch( int array2[], int key ) { // loop through array elements for ( int counter = 0 ; counter < array2.length; counter++ ) // if array element equals key value, return location if ( array2[ counter ] == key ) return counter; return -1; // key not found } // end method linearsearch 60 // obtain user input and call method linearsearch 61 public void actionperformed( ActionEvent actionevent ) 62 { 63 // input also can be obtained with enterfield.gettext() 64 String searchkey = actionevent.getactioncommand(); 65 66 67 68 // pass array reference to linearsearch; normally, a reference to an // array is passed to a method to search corresponding array object int element = linearsearch( array, Integer.parseInt( searchkey ) ); 69 70 // display search result 71 if ( element!= -1 ) 72 resultfield.settext( "Found value in element " + element ); 73 else 74 resultfield.settext( "Value not found" ); 75 76 } // method actionperformed 77 78 } // end class LinearSearch Fig. 7.11 Linear search of an array. (Part 2 of 2.) Searching a Sorted Array with Binary Search The linear-search method works well for small arrays or for unsorted arrays. However, for large arrays, linear searching is inefficient. If the array is sorted, the high-speed binarysearch technique can be used.

302 Arrays Chapter 7 As we saw in the previous example, the linear-search algorithm compares the search key with an average of half the elements in the array. However, the binary-search algorithm eliminates half of the elements in the array being searched after each comparison. The algorithm locates the middle array element and compares it with the search key. If they are equal, the search key has been found, and the binary search returns the index of that element. Otherwise, the binary search reduces the problem to searching half of the sorted array. If the search key is less than the middle array element, the first half of the array will be searched; otherwise, the second half of the array will be searched. 4 If the search key is not the middle element in the specified subarray (i.e., part of the original array), the algorithm repeats on one quarter of the original array. The search continues until the search key is equal to the middle element of a subarray or until the subarray consists of one element that is not equal to the search key (i.e., the search key is not found). In the worst-case scenario, searching a sorted array of 1023 elements will take only 10 comparisons when using a binary search. Repeatedly dividing 1024 by 2 (because after each comparison, we are able to eliminate half of the array) yields the values 512, 256, 128, 64, 32, 16, 8, 4, 2 and 1. The number 1024 (2 10 ) is divided by 2 only 10 times to get the value 1. Dividing by 2 is equivalent to one comparison in the binary-search algorithm. Thus, an array of 1,048,576 (2 20 ) elements takes a maximum of 20 comparisons to find the key, and an array of one billion elements takes a maximum of 30 comparisons to find the key. This is a tremendous increase in performance over the linear search. For a one-billionelement array, this is a difference between an average of 500 million comparisons and a maximum of 30 comparisons! The maximum number of comparisons needed for the binary search of any sorted array is the exponent of the first power of 2 greater than the number of elements in the array. Figure 7.12 presents an iterative binarysearch method (lines 78 108) that receives as arguments an integer array called array2 (the array to search) and an integer key (the search key). The program passes a reference to the array to method binarysearch. Once again, we do this because a reference to an array normally is passed to a method of another class to search the corresponding array. In binarysearch, if key matches the middle element of a subarray, binarysearch returns middle (the index of the current element) to indicate that the value was found and the search is complete. If key does not match the middle element of a subarray, binarysearch adjusts the low index or high index (both declared in the method), to continue the search, using a smaller subarray. If key is less than the middle element, the high index is set to middle -1, and the search continues on the elements from low to middle -1. If key is greater than the middle element, the low index is set to middle +1, and the search continues on the elements from middle +1 to high. The nested if else statement at lines 93 102 performs these comparisons. 1 // Fig. 7.12: BinarySearch.java 2 // Binary search of an array. 3 import java.awt.*; 4 import java.awt.event.*; 5 import java.text.*; Fig. 7.12 Binary search of a sorted array. (Part 1 of 5.) 4. This example assumes that the array is sorted in ascending order.

Chapter 7 Arrays 303 6 7 import javax.swing.*; 8 9 public class BinarySearch extends JApplet implements ActionListener { 10 JLabel enterlabel, resultlabel; 11 JTextField enterfield, resultfield; 12 JTextArea output; 13 14 int array[]; 15 String display = ""; 16 17 // set up applet's GUI 18 public void init() 19 { 20 // get content pane and set its layout to FlowLayout 21 Container container = getcontentpane(); 22 container.setlayout( new FlowLayout() ); 23 24 // set up JLabel and JTextField for user input 25 enterlabel = new JLabel( "Enter integer search key" ); 26 container.add( enterlabel ); 27 28 enterfield = new JTextField( 10 ); 29 container.add( enterfield ); 30 31 // register this applet as enterfield's action listener 32 enterfield.addactionlistener( this ); 33 34 // set up JLabel and JTextField for displaying results 35 resultlabel = new JLabel( "Result" ); 36 container.add( resultlabel ); 37 38 resultfield = new JTextField( 20 ); 39 resultfield.seteditable( false ); 40 container.add( resultfield ); 41 42 // set up JTextArea for displaying comparison data 43 output = new JTextArea( 6, 60 ); 44 45 output.setfont( new Font( "Monospaced", Font. PLAIN, 12 ) ); container.add( output ); 46 47 // create array and fill with even integers 0 to 28 48 array = new int [ 15 ]; 49 50 for ( int counter = 0 ; counter < array.length; counter++ ) 51 array[ counter ] = 2 * counter; 52 53 } // end method init 54 55 // obtain user input and call method binarysearch 56 public void actionperformed( ActionEvent actionevent ) 57 { Fig. 7.12 Binary search of a sorted array. (Part 2 of 5.)

304 Arrays Chapter 7 58 // input also can be obtained with enterfield.gettext() 59 String searchkey = actionevent.getactioncommand(); 60 61 // initialize display string for new search 62 display = "Portions of array searched\n"; 63 64 65 66 67 output.settext( display ); 68 69 // display search result 70 if ( element!= -1 ) 71 resultfield.settext( "Found value in element " + element ); 72 else 73 resultfield.settext( "Value not found" ); 74 75 } // end method actionperformed 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 // perform binary search int element = binarysearch( array, Integer.parseInt( searchkey ) ); // method to perform binary search of an array public int binarysearch( int array2[], int key ) { int low = 0 ; // low element index int high = array2.length - 1 ; // high element index int middle; // middle element index // loop until low index is greater than high index while ( low <= high ) { middle = ( low + high ) / 2 ; // determine middle index // display subset of array elements used in this // iteration of binary search loop buildoutput( array2, low, middle, high ); // if key matches middle element, return middle location if ( key == array[ middle ] ) return middle; // if key less than middle element, set new high element else if ( key < array[ middle ] ) high = middle - 1 ; // key greater than middle element, set new low element else low = middle + 1 ; } // end while return -1; // key not found } // end method binarysearch Fig. 7.12 Binary search of a sorted array. (Part 3 of 5.)

Chapter 7 Arrays 305 110 // build row of output showing subset of array elements 111 // currently being processed 112 void buildoutput( int array3[], int low, int middle, int high ) 113 { 114 // create 2-digit integer number format 115 DecimalFormat twodigits = new DecimalFormat( "00" ); 116 117 // loop through array elements 118 for ( int counter = 0 ; counter < array3.length; counter++ ) { 119 120 // if counter outside current array subset, append 121 // padding spaces to String display 122 if ( counter < low counter > high ) 123 display += " " ; 124 125 // if middle element, append element to String display 126 // followed by asterisk (*) to indicate middle element 127 else if ( counter == middle ) 128 display += twodigits.format( array3[ counter ] ) + "* " ; 129 130 else // append element to String display 131 display += twodigits.format( array3[ counter ] ) + " " ; 132 133 } // end for 134 135 display += "\n"; 136 137 } // end method buildoutput 138 139 } // end class BinarySearch Fig. 7.12 Binary search of a sorted array. (Part 4 of 5.)

306 Arrays Chapter 7 Fig. 7.12 Binary search of a sorted array. (Part 5 of 5.) This program uses a 15-element array. The first power of 2 greater than the number of elements is 16 (2 4 ), so binarysearch requires at most four comparisons to find the key. To illustrate this, line 90 calls method buildoutput (declared at lines 112 137) to output each subarray during the binary-search process. Method buildoutput marks the middle element in each subarray with an asterisk ( * ) to indicate the element with which the key is compared. No matter what search key is entered, each search in this example results in a maximum of four lines of output one per comparison. Textarea output uses Monospaced font (a fixed-width font i.e., all characters are the same width) to help align the displayed text in each line of output. Line 44 uses method setfont to change the font displayed in output. Method setfont can change the font of text displayed on most GUI components. The method requires a Font (package java.awt) object as its argument. A Font object is initialized with three arguments the String name of the font ( "Monospaced"), an int representing the style of the font ( Font.PLAIN is a constant integer declared in class Font that indicates plain font) and an int representing the point size of the font (12 ). Java provides generic names for several fonts available on every Java platform. Monospaced font is also called Courier. Other common fonts include Serif (also called TimesRoman ) and SansSerif (also called Helvetica). Java provides access to all fonts on your system via methods of class Graphics- Environment (package java.awt). The style can also be Font.BOLD, Font.ITALIC or Font.BOLD +Font.ITALIC. The point size represents the size of the font. There are 72 points to an inch. The actual size of the text as it appears on the screen may vary based on the size of the screen and the screen resolution. 7.9 Multidimensional Arrays Multidimensional arrays with two dimensions are often used to represent tables of values consisting of information arranged in rows and columns. To identify a particular table element, we must specify two indices. By convention, the first identifies the element s row and the second identifies the element s column. Arrays that require two indices to identify a particular element are called two-dimensional arrays. (Multidimensional arrays can have more than two dimensions.) Java does not support multidimensional arrays directly, but does allow the programmer to specify one-dimensional arrays whose elements are also one-dimensional arrays, thus achieving the same effect. Figure 7.13 illustrates a two-dimensional array

Chapter 7 Arrays 307 Row 0 Row 1 Row 2 Column 0 Column 1 Column 2 Column 3 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ] a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ] a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ] Column index Row index Array name Fig. 7.13 Two-dimensional array with three rows and four columns. a that contains three rows and four columns (i.e., a three-by-four array). In general, an array with m rows and n columns is called an m-by-n array. Every element in array a is identified in Fig. 7.13 by an array-access expression of the form a[ row ][ column ] ; a is the name of the array reference, and row and column are the indices that uniquely identify each element in array a by row and column number. Notice that the names of the elements in the first row all have a first index of 0 ; the names of the elements in the fourth column all have a second index of 3. Arrays of One-Dimensional Arrays Like one-dimensional arrays, multidimensional arrays can be initialized with array initializers in declarations. A two-dimensional array b with two rows and two columns could be declared and initialized with nested array initializers as follows: int b[][] = { { 1, 2 }, { 3, 4 } }; The initializer values are grouped by row in braces. So, 1 and 2 initialize b[ 0][ 0] and b[ 0][ 1], and 3 and 4 initialize b[ 1][ 0] and b[ 1][ 1]. The compiler determines the number of rows by counting the number of nested array initializers (represented by sets of braces within the outer braces) in the array initializer. The compiler determines the number of columns in a row by counting the initializer values in the array initializer for that row. In Java, multidimensional arrays are maintained as arrays of one-dimensional arrays. So, the array b in the preceding declaration is actually composed of three separate onedimensional arrays. The array b itself is a one-dimensional array containing two elements. Each element is a reference to a one-dimensional array of int variables. Two-Dimensional Arrays with Rows of Different Lengths The manner in which Java represents multidimensional arrays makes them quite flexible. In fact, the lengths of the rows in array b are not required to be the same. For example, int b[][] = { { 1, 2 }, { 3, 4, 5 } }; creates integer array b with two elements (determined by the number of nested array initializers) that represent the rows of the two-dimensional array. Each element of b is a ref-

308 Arrays Chapter 7 erence to a one-dimensional array of int variables. The int array for row 0 is a onedimensional array with two elements (1 and 2 ) and the int array for row 1 is a one-dimensional array with three elements ( 3, 4 and 5 ). Creating Two-Dimensional Arrays with Array-Creation Expressions A multidimensional array with the same number of columns in every row can be created with an array-creation expression. For example, the following lines declare array b and assign it a reference to a three-by-four array: int b[][]; b = new int [ 3 ][ 4 ]; In this case, we use the literal values 3 and 4 to specify the number of rows and number of columns, respectively, but this is not required. Programs also can use variables to specify array dimensions. As with one-dimensional arrays, the elements of a multidimensional array are initialized when the array object is created. A multidimensional array in which each row has a different number of columns can be created as follows: int b[][]; b = new int [ 2 ][ ]; // create 2 rows b[ 0 ] = new int [ 5 ]; // create 5 columns for row 0 b[ 1 ] = new int [ 3 ]; // create 3 columns for row 1 The preceding statements create a two-dimensional array with two rows. Row 0 has five columns, and row 1 has three columns. Two-Dimensional Array Example: Displaying Element Values The applet of Fig. 7.14 demonstrates initializing two-dimensional arrays with array initializers and using nested for loops (lines 31 38) to traverse the arrays (i.e., manipulate every element of each array). 1 // Fig. 7.14: InitArray.java 2 // Initializing two-dimensional arrays. 3 import java.awt.container; 4 import javax.swing.*; 5 6 public class InitArray extends JApplet { 7 JTextArea outputarea; 8 9 // set up GUI and initialize applet 10 public void init() 11 { 12 outputarea = new JTextArea(); 13 Container container = getcontentpane(); 14 container.add( outputarea ); 15 16 17 int array1[][] = { { 1, 2, 3 }, { 4, 5, 6 } }; int array2[][] = { { 1, 2 }, { 3 }, { 4, 5, 6 } }; Fig. 7.14 Initializing two-dimensional arrays. (Part 1 of 2.)

Chapter 7 Arrays 309 18 19 outputarea.settext( "Values in array1 by row are\n" ); 20 buildoutput( array1 ); 21 22 outputarea.append( "\nvalues in array2 by row are\n" ); 23 buildoutput( array2 ); 24 25 } // end method init 26 27 // append rows and columns of an array to outputarea 28 public void buildoutput( int array[][] ) 29 { 30 31 32 33 34 35 36 37 outputarea.append( "\n" ); 38 } 39 // loop through array's rows for ( int row = 0 ; row < array.length; row++ ) { // loop through columns of current row for ( int column = 0 ; column < array[ row ].length; column++ ) outputarea.append( array[ row ][ column ] + " " ); 40 } // end method buildoutput 41 42 } // end class InitArray Fig. 7.14 Initializing two-dimensional arrays. (Part 2 of 2.) The program declares two arrays in method init. The declaration of array1 (line 16) uses nested array initializers to initialize the first row of the array to the values 1, 2 and 3, and the second row of the array to the values 4, 5 and 6. The declaration of array2 (line 17) uses nested initializers of different lengths. In this case, the first row is initialized to have two elements with values 1 and 2, respectively. The second row is initialized to have one element with value 3. The third row is initialize to have three elements with the values 4, 5 and 6, respectively. Line 20 of method init calls method buildoutput (declared in lines 28 40) to append each array s elements to textarea outputarea. Method buildoutput specifies the array parameter as int array[][] to indicate that the method receives a two-dimensional array as an argument. The nested for statement (lines 31 38) outputs the rows of a two-dimensional array. In the outer for statement, the expression array.length deter-

310 Arrays Chapter 7 mines the number of rows in the array. In the inner for statement, the expression array[ row ].length determines the number of columns in the current row of the array. This condition enables the loop to determine the exact number of columns in each row. Common Multidimensional-Array Manipulations Performed with for Statements Many common array manipulations use for statements. As an example, the following for statement sets all the elements in the third row of array a in Fig. 7.13 to zero: for ( int column = 0 ; column < a[ 2 ].length; column++) a[ 2 ][ column ] = 0 ; We specified the third row; therefore, we know that the first index is always 2 ( 0 is the first row, and 1 is the second row). This for loop varies only the second index (i.e., the column index). The preceding for statement is equivalent to the assignment statements a[ 2 ][ 0 ] = 0 ; a[ 2 ][ 1 ] = 0 ; a[ 2 ][ 2 ] = 0 ; a[ 2 ][ 3 ] = 0 ; The following nested for statement totals the values of all the elements in array a : int total = 0 ; for ( int row = 0 ; row < a.length; row++ ) for ( int column = 0 ; column < a[ row ].length; column++ ) total += a[ row ][ column ]; This for statement totals the array elements one row at a time. The outer for statement begins by setting the row index to 0 so that the elements of the first row may be totaled by the inner for statement. The outer for statement then increments row to 1 so that the second row can be totaled. Then, the outer for statement increments row to 2 so that the third row can be totaled. The result can be displayed when the nested for statement terminates. Two-Dimensional Array Example: Summarizing Student s Exam Grades The applet of Fig. 7.15 performs several other common array manipulations on the threeby-four array grades. Each row of the array represents a student, and each column represents a grade on one of the four exams the students took during the semester. Four methods perform the array manipulations. Method minimum (lines 48 65) determines the lowest grade of any student for the semester. Method maximum (lines 68 85) determines the highest grade of any student for the semester. Method average (lines 88 99) determines a particular student s semester average. Method buildstring (lines 102 118) appends the two-dimensional array to string output in a tabular format. Methods minimum, maximum and buildstring each use array grades and the variables students (number of rows in the array) and exams (number of columns in the array). Each method loops through array grades by using nested for statements for example, the nested for statement from the declaration of method minimum (lines 54 61). The outer for statement sets row (the row index) to 0 so that the elements of the first row can be compared with variable lowgrade in the body of the inner for statement. The inner

Chapter 7 Arrays 311 1 // Fig. 7.15: DoubleArray.java 2 // Two-dimensional array example. 3 import java.awt.*; 4 import javax.swing.*; 5 6 public class DoubleArray extends JApplet { 7 8 9 10 11 int students, exams; 12 String output; 13 JTextArea outputarea; 14 15 // initialize fields 16 public void init() 17 { 18 students = grades.length; // number of students 19 exams = grades[ 0 ].length; // number of exams 20 21 // create JTextArea and attach to applet 22 outputarea = new JTextArea(); 23 Container container = getcontentpane(); 24 container.add( outputarea ); 25 26 // build output string 27 output = "The array is:\n"; 28 29 int grades[][] = { { 77, 68, 86, 73 }, { 96, 87, 89, 81 }, { 70, 90, 86, 81 } }; buildstring(); 30 // call methods minimum and maximum 31 output += "\n\nlowest grade: " + minimum() + 32 "\nhighest grade: " + maximum() + "\n"; 33 34 // call method average to calculate each student's average 35 for ( int counter = 0 ; counter < students; counter++ ) 36 output += "\naverage for student " + counter + " is " + 37 38 39 // change outputarea's display font average( grades[ counter ] ); // pass one row of array grades 40 outputarea.setfont( new Font( "Monospaced", Font. PLAIN, 12 ) ); 41 42 // place output string in outputarea 43 outputarea.settext( output ); 44 45 } // end method init 46 47 // find minimum grade 48 public int minimum() 49 { 50 // assume first element of grades array is smallest 51 int lowgrade = grades[ 0 ][ 0 ]; 52 Fig. 7.15 Two-dimensional arrays. (Part 1 of 3.)

312 Arrays Chapter 7 53 // loop through rows of grades array 54 for ( int row = 0 ; row < students; row++ ) 55 56 // loop through columns of current row 57 for ( int column = 0 ; column < exams; column++ ) 58 59 // if grade is less than lowgrade, assign it to lowgrade 60 if ( grades[ row ][ column ] < lowgrade ) 61 lowgrade = grades[ row ][ column ]; 62 63 return lowgrade; // return lowest grade 64 65 } // end method minimum 66 67 // find maximum grade 68 public int maximum() 69 { 70 // assume first element of grades array is largest 71 int highgrade = grades[ 0 ][ 0 ]; 72 73 // loop through rows of grades array 74 for ( int row = 0 ; row < students; row++ ) 75 76 // loop through columns of current row 77 for ( int column = 0 ; column < exams; column++ ) 78 79 // if grade is greater than highgrade, assign it to highgrade 80 if ( grades[ row ][ column ] > highgrade ) 81 highgrade = grades[ row ][ column ]; 82 83 return highgrade; // return highest grade 84 85 } // end method maximum 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 // determine average grade for particular student (or set of grades) public double average( int setofgrades[] ) { int total = 0 ; // initialize total // sum grades for one student for ( int count = 0 ; count < setofgrades.length; count++ ) total += setofgrades[ count ]; // return average of grades return ( double ) total / setofgrades.length; } // end method average 101 // build output string 102 public void buildstring() 103 { 104 output += " " ; // used to align column heads 105 Fig. 7.15 Two-dimensional arrays. (Part 2 of 3.)

Chapter 7 Arrays 313 106 // create column heads 107 for ( int counter = 0 ; counter < exams; counter++ ) 108 output += "[" + counter + "] " ; 109 110 // create rows/columns of text representing array grades 111 for ( int row = 0 ; row < students; row++ ) { 112 output += "\ngrades[" + row + "] " ; 113 114 for ( int column = 0 ; column < exams; column++ ) 115 output += grades[ row ][ column ] + " " ; 116 } 117 118 } // end method buildstring 119 120 } // end class DoubleArray Fig. 7.15 Two-dimensional arrays. (Part 3 of 3.) for statement loops through the four grades of a particular row and compares each grade with lowgrade. If a grade is less than lowgrade, lowgrade is set to that grade. The outer for statement then increments the row index by 1, and the elements of the second row are compared with variable lowgrade. The outer for statement then increments the row index to 2, and the elements of the third row are compared with variable lowgrade. When execution of the nested statement is complete, lowgrade contains the smallest grade in the two-dimensional array. Method maximum works similarly to method minimum. Method average takes one argument a one-dimensional array of test results for a particular student. When line 37 calls average, the argument is grades[ counter ], which specifies that a particular row of the two-dimensional array grades should be passed to average. For example, the argument grades[ 1] represents the four values (a one-dimensional array of grades) stored in the second row of the two-dimensional array grades. Remember that, in Java, a two-dimensional array is an array with elements that are one-dimensional arrays. Method average calculates the sum of the array elements, divides the total by the number of test results and returns the floating-point result as a double value (line 97).