 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 7 - Arrays Outline 7.1Introduction 7.2Arrays 7.3Declaring and Allocating Arrays 7.4Examples Using.

Slides:



Advertisements
Similar presentations
Arrays. Introduction Arrays –Structures of related data items –Static entity - same size throughout program A few types –C-like, pointer-based arrays.
Advertisements

 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
 2003 Prentice Hall, Inc. All rights reserved. 7.1 Introduction Arrays –Data structures which reference one or more value –All items must have same data.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 7 - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Creating Arrays 7.4 Examples.
Chapter 7 - Arrays Outline 7.1Introduction 7.2Arrays 7.3Declaring and Allocating Arrays 7.4Examples Using Arrays 7.5References and Reference Parameters.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 25 - Beyond C & C++: Operators, Methods, and Arrays in Java Outline 25.1Introduction 25.2Primitive.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
 2003 Prentice Hall, Inc. All rights reserved Introduction Arrays –Structures of related data items –Static entity (same size throughout program)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
Review (Week1) C++_ the unit of programming is the class from which objects are eventually instantiated. C++ classes contain functions that implement class.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 7 - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Creating Arrays 7.4 Examples Using.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays 6.3Declaring Arrays 6.4Examples Using Arrays 6.5Passing.
 2003 Prentice Hall, Inc. All rights reserved. 1 Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
 2003 Prentice Hall, Inc. All rights reserved Multiple-Subscripted Arrays Multiple subscripts –a[ i ][ j ] –Tables with rows and columns –Specify.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Arrays Dale Roberts, Lecturer
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
 2003 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Arrays Introduction to Computers and Programming in.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
School of Computing Science CMT1000 © Ed Currie Middlesex University Lecture 9: 1 CMT1000: Introduction to Programming Ed Currie Lecture 9: Arrays.
1 JavaScript/Jscript: Arrays. 2 Introduction Arrays –Data structures consisting of related data items (collections of data items) JavaScript arrays are.
Chapter 7 - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Creating Arrays 7.4 Examples Using Arrays 7.5 References and Reference Parameters.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
 2002 Prentice Hall. All rights reserved. Chapter 7 - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Allocating Arrays 7.4 Examples Using.
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - JavaScript: Arrays Outline 11.1 Introduction 11.2 Arrays 11.3 Declaring and Allocating Arrays.
1 Chapter 7 - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Allocating Arrays 7.4 Examples Using Arrays Allocating an Array and Initializing.
8/9: Multiple-Subscripted Arrays About BinarySearch.java Multiple-Subscripted Arrays Program of the Day.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
11/9: Recursion, Method Overloading About Scoping.java Recursion Method overloading.
4/15: Searching Arrays Look at BubbleSort.java Searching arrays: the linear search Searching arrays: the binary search.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 19 Thanks for Lecture Slides:
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades.
Chapter 6 Arrays Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Algorithm and Programming Array Dr. Ir. Riri Fitri Sari MM MSc International Class Electrical Engineering Dept University of Indonesia 15 March 2009.
11/15: Ch. 7: Arrays What is an array? Declaring & allocating arrays Sorting & searching arrays.
C Lecture Notes 1 Arrays Lecture 6. C Lecture Notes 2 6.1Introduction Arrays –Structures of related data items –Static entity – same size throughout program.
1 Arrays as Lists with examples. 2 Review Arrays –Structures of related data items of the same type –Data items (called array elements) are stored at.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
1 Lecture 8 Arrays Part II Sorting Arrays Sorting data  Important computing application  Virtually every organization must sort some data Massive.
1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing Arrays to Functions 4.6Sorting Arrays 4.7Case.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays.
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.
4/17: Multiple-Subscripted Arrays About BinarySearch.java Multiple-Subscripted Arrays Program of the Day.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
 2002 Prentice Hall. All rights reserved. Chapter 7 - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Allocating Arrays 7.4 Examples Using.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 7 - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Creating Arrays 7.4 Examples.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
C Lecture Notes 1 Arrays (...cont.). C Lecture Notes 2 6.6Sorting Arrays Sorting data –Important computing application –Virtually every organization must.
 2003 Prentice Hall, Inc. All rights reserved. Outline 1 fig04_03.cpp (1 of 2) 1 // Fig. 4.3: fig04_03.cpp 2 // Initializing an array. 3 #include 4 5.
11/30: Sorting and Searching Arrays Look at PassArray.java Sorting arrays: the bubble sort method Searching arrays: the linear search Searching arrays:
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
CHAPTER 3 ARRAYS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Arrays 3.Declaring Arrays 4.Examples Using Arrays 5.Multidimensional Arrays 6.Multidimensional.
8/8: Sorting and Searching Arrays Look at PassArray.java Sorting arrays: the bubble sort method Searching arrays: the linear search Searching arrays: the.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
 2000 Prentice Hall, Inc. All rights reserved Arrays Array –Consecutive group of memory locations –Same name and type To refer to an element, specify.
CSC 113: C OMPUTER P ROGRAMMING (T HEORY = 03, L AB = 01) Computer Science Department Bahria University, Islamabad.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Arrays + Functions Outline 6.5Passing Arrays to Functions.
Chapter 7 - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Allocating Arrays 7.4 Examples Using Arrays Allocating an Array and Initializing.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - JavaScript: Arrays Outline 11.1 Introduction 11.2 Arrays 11.3 Declaring and Allocating Arrays.
Lecture 4: Chapter 7 - Arrays Outline Declaring and Creating Arrays Examples Using Arrays References and Reference Parameters Passing Arrays to Methods.
Chapter 7 - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Allocating Arrays 7.4 Examples Using Arrays Allocating an Array.
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
Chapter 7 - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Creating Arrays 7.4 Examples Using Arrays 7.5 References and Reference.
Arrays Outline Introduction Arrays Declaring Arrays
CISC181 Introduction to Computer Science Dr
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
Capitolo 4 - Arrays Outline 4.1 Introduction 4.2 Arrays
Chapter 3 Arrays Dr. A. PHILIP AROKIADOSS Assistant Professor
Presentation transcript:

 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 7 - Arrays Outline 7.1Introduction 7.2Arrays 7.3Declaring and Allocating Arrays 7.4Examples Using Arrays 7.5References and Reference Parameters 7.6Passing Arrays to Methods 7.7Sorting Arrays 7.8Searching Arrays: Linear Search and Binary Search 7.9Multiple-Subscripted Arrays

 2000 Prentice Hall, Inc. All rights reserved Introduction Arrays –Data structures –Contain several related items of same type –Static Remain same size –In later chapters, discuss dynamic array-like classes Can grow and shrink

 2000 Prentice Hall, Inc. All rights reserved Arrays Array –Group of consecutive memory locations –Same name and type To refer to an element, specify –Array name –Position number Format : –arrayname [ position number ] –First element at position 0 –n element array named c : c[0], c[1]... c[n-1] Subscript

 2000 Prentice Hall, Inc. All rights reserved Arrays c[6] Name of array (Note that all elements of this array have the same name, c) c[0] c[1] c[2] c[3] c[11] c[10] c[9] c[8] c[7] c[5] c[4] Position number of the element within array c

 2000 Prentice Hall, Inc. All rights reserved Arrays Arrays –Every array knows its own length c.length –Elements are like normal variables c[ 0 ] = 3; c[ 0 ] += 5; –Can perform operations in subscript If x = 3, c[ ] == c[ 3 ] == c[ x ]

 2000 Prentice Hall, Inc. All rights reserved Declaring and Allocating Arrays Declaring arrays –Specify type, use new operator Allocate number of elements Place brackets after name in declaration –Two steps: int c[]; //declaration c = new int[ 12 ]; //allocation –One step: int c[] = new int[ 12 ]; –Primitive elements initialized to zero or false Non-primitive references are null

 2000 Prentice Hall, Inc. All rights reserved Declaring and Allocating Arrays Multiple declarations String b[] = new String[ 100 ], x[] = new String[ 27 ]; –Declaring multiple arrays of same type Can put brackets after data type instead of after name double[] array1, array2; Arrays –Can contain any data type –For non-primitive types, every element a reference to an object

 2000 Prentice Hall, Inc. All rights reserved Examples Using Arrays new –Dynamically creates arrays length –Length of the array myArray.length Initializer lists int myArray[] = { 1, 2, 3, 4, 5 }; new operator not needed, provided automatically Initializes 5 element integer array with values shown

 2000 Prentice Hall, Inc. All rights reserved. Outline 9 1. main 1.1 Initializer list 2. Loop 3. GUI 1// Fig. 7.4: InitArray.java 2// initializing an array with a declaration 3import javax.swing.*; 4 5public class InitArray { 6 public static void main( String args[] ) 7 { 8 String output = ""; 9 10 // Initializer list specifies number of elements and 11 // value for each element int n[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; output += "Subscript\tValue\n"; for ( int i = 0; i < n.length; i++ ) 17 output += i + "\t" + n[ i ] + "\n"; JTextArea outputArea = new JTextArea( 11, 10 ); 20 outputArea.setText( output ); JOptionPane.showMessageDialog( null, outputArea, 23 "Initializing an Array with a Declaration", 24 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); 27 } 28} Notice how the initializer list is used ( new not needed). n.length is the length of the array. The length is one greater than the highest subscript.

 2000 Prentice Hall, Inc. All rights reserved. Outline 10 Program Output

 2000 Prentice Hall, Inc. All rights reserved Examples Using Arrays Dice-rolling program –Use an array to keep track of which number was rolled –7 element array (subscripts 0 to 6) –When a number is rolled, increment that array element

 2000 Prentice Hall, Inc. All rights reserved. Outline main 1.1 Initialize frequency array 2. Loop 2.1 Math.random 2.2 Update frequency 3. Display results 1// Fig. 7.9: RollDie.java 2// Roll a six-sided die 6000 times 3import javax.swing.*; 4 5public class RollDie { 6 public static void main( String args[] ) 7 { 8 int face, frequency[] = new int[ 7 ]; 9 String output = ""; for ( int roll = 1; roll <= 6000; roll++ ) { 12 face = 1 + ( int ) ( Math.random() * 6 ); frequency[ face ]; 14 } output += "Face\tFrequency"; for ( face = 1; face < frequency.length; face++ ) 19 output += "\n" + face + "\t" + frequency[ face ]; JTextArea outputArea = new JTextArea( 7, 10 ); 22 outputArea.setText( output ); JOptionPane.showMessageDialog( null, outputArea, 25 "Rolling a Die 6000 Times", 26 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); 29 } 30} All elements start at zero (primitive data type). Increment proper location when die rolled.

 2000 Prentice Hall, Inc. All rights reserved. Outline 13 Program Output

 2000 Prentice Hall, Inc. All rights reserved References and Reference Parameters Passing arguments to methods –Call-by-value: pass copy of argument –Call-by-reference: pass original argument Improves performance, weakens security In Java, cannot choose how to pass arguments –Primitive data types passed call-by-value –References to objects passed call-by-reference Original object can be changed in method –Arrays in Java treated as objects Passed call-by-reference

 2000 Prentice Hall, Inc. All rights reserved Passing Arrays to Functions Passing arrays –Specify array name without brackets int myArray[ 24 ]; myFunction( myArray ); –Arrays passed call-by-reference Modifies original memory locations –Header for method modifyArray might be void modifyArray( int b[] ) Passing array elements –Passed by call-by-value –Pass subscripted name (i.e., myArray[3] ) to method

 2000 Prentice Hall, Inc. All rights reserved. Outline init 1.1 GUI 1.2 Initialize array 2. modifyArray 1// Fig. 7.10: PassArray.java 2// Passing arrays and individual array elements to methods 3import java.awt.Container; 4import javax.swing.*; 5 6public class PassArray extends JApplet { 7 JTextArea outputArea; 8 String output; 9 10 public void init() 11 { 12 outputArea = new JTextArea(); 13 Container c = getContentPane(); 14 c.add( outputArea ); int a[] = { 1, 2, 3, 4, 5 }; output = "Effects of passing entire " + 19 "array call-by-reference:\n" + 20 "The values of the original array are:\n"; for ( int i = 0; i < a.length; i++ ) 23 output += " " + a[ i ]; modifyArray( a ); // array a passed call-by-reference output += "\n\nThe values of the modified array are:\n"; Arrays are passed call-by-reference, so modifyArray will alter the original array.

 2000 Prentice Hall, Inc. All rights reserved. Outline modifyElement 4. modifyArray definition 4.1 modifyElement definition for ( int i = 0; i < a.length; i++ ) 30 output += " " + a[ i ]; output += "\n\nEffects of passing array " + 33 "element call-by-value:\n" + 34 "a[3] before modifyElement: " + a[ 3 ]; modifyElement( a[ 3 ] ); output += "\na[3] after modifyElement: " + a[ 3 ]; 39 outputArea.setText( output ); 40 } public void modifyArray( int b[] ) 43 { 44 for ( int j = 0; j < b.length; j++ ) 45 b[ j ] *= 2; 46 } public void modifyElement( int e ) 49 { 50 e *= 2; 51 } 52} Individual elements passed call-by-value, so only a copy is modified.

 2000 Prentice Hall, Inc. All rights reserved. Outline 18 Program Output

 2000 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort some data Massive amounts must be sorted Bubble sort (sinking sort) –Several passes through the array –Successive pairs of elements are compared If increasing order (or identical ), no change If decreasing order, elements exchanged –Repeat –Easy to program, but runs slowly

 2000 Prentice Hall, Inc. All rights reserved Sorting Arrays Example Original: pass 1: pass 2: –Small elements "bubble" to the top

 2000 Prentice Hall, Inc. All rights reserved. Outline init 1.1 GUI 1.2 Initialize array 2. bubbleSort 1// Fig. 7.11: BubbleSort.java 2// This program sorts an array's values into 3// ascending order 4import java.awt.*; 5import javax.swing.*; 6 7public class BubbleSort extends JApplet { 8 public void init() 9 { 10 JTextArea outputArea = new JTextArea(); 11 Container c = getContentPane(); 12 c.add( outputArea ); int a[] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; String output = "Data items in original order\n"; for ( int i = 0; i < a.length; i++ ) 19 output += " " + a[ i ]; bubbleSort( a ); output += "\n\nData items in ascending order\n"; for ( int i = 0; i < a.length; i++ ) 26 output += " " + a[ i ]; outputArea.setText( output ); 29 } 30

 2000 Prentice Hall, Inc. All rights reserved. Outline bubbleSort definition 4. swap definition 31 // sort the elements of an array with bubble sort public void bubbleSort( int b[] ) 33 { 34 for ( int pass = 1; pass < b.length; pass++ ) // passes 35 for ( int i = 0; i < b.length - 1; i++ ) // one pass 36 if ( b[ i ] > b[ i + 1 ] ) // one comparison 37 swap( b, i, i + 1 ); // one swap 38 } // swap two elements of an array public void swap( int c[], int first, int second ) 42 { 43 int hold; // temporary holding area for swap hold = c[ first ]; 46 c[ first ] = c[ second ]; 47 c[ second ] = hold; 48 } 49} Have b.length passes, each pass makes b.length comparisons. If out of order, swap elements. Use temporary holding area to swap elements. Notice how the function takes an array and two elements as arguments.

 2000 Prentice Hall, Inc. All rights reserved. Outline 23 Program Output

 2000 Prentice Hall, Inc. All rights reserved Searching Arrays: Linear Search and Binary Search Search an array for a key value Linear search –Simple –Compare each element of array with key value –Useful for small and unsorted arrays

 2000 Prentice Hall, Inc. All rights reserved Searching Arrays: Linear Search and Binary Search Binary search –For sorted arrays –Compares middle element with key If equal, match found If key < middle, looks in first half of array If key > middle, looks in last half Repeat –Very fast, at most n steps, where 2 > number of elements 30 element array takes at most 5 steps 2 > 30 n 5

 2000 Prentice Hall, Inc. All rights reserved. Outline import 2. init 2.1 GUI 2.2 Register event handler 1// Fig. 7.12: LinearSearch.java 2// Linear search of an array 3import java.awt.*; 4import java.awt.event.*; 5import javax.swing.*; 6 7public class LinearSearch extends JApplet 8 implements ActionListener { 9 JLabel enterLabel, resultLabel; 10 JTextField enter, result; 11 int a[]; public void init() 14 { 15 Container c = getContentPane(); 16 c.setLayout( new FlowLayout() ); enterLabel = new JLabel( "Enter integer search key" ); 19 c.add( enterLabel ); enter = new JTextField( 10 ); 22 enter.addActionListener( this ); 23 c.add( enter ); resultLabel = new JLabel( "Result" ); 26 c.add( resultLabel ); result = new JTextField( 20 ); 29 result.setEditable( false ); 30 c.add( result );

 2000 Prentice Hall, Inc. All rights reserved. Outline Create and initialize array 3. linearSearch definition 4. Event handler // create array and populate with even integers 0 to a = new int[ 100 ]; for ( int i = 0; i < a.length; i++ ) 36 a[ i ] = 2 * i; } // Search "array" for the specified "key" value public int linearSearch( int array[], int key ) 42 { 43 for ( int n = 0; n < a.length; n++ ) 44 if ( array[ n ] == key ) 45 return n; return -1; 48 } public void actionPerformed( ActionEvent e ) 51 { 52 String searchKey = e.getActionCommand(); // Array a is passed to linearSearch even though it 55 // is an instance variable. Normally an array will 56 // be passed to a method for searching. 57 int element = 58 linearSearch( a, Integer.parseInt( searchKey ) ); 59 Linear searching compares each element to the key value.

 2000 Prentice Hall, Inc. All rights reserved. Outline Event handler Program Output 60 if ( element != -1 ) 61 result.setText( "Found value in element " + 62 element ); 63 else 64 result.setText( "Value not found" ); 65 } 66}

 2000 Prentice Hall, Inc. All rights reserved Searching Arrays: Linear Search and Binary Search –Sets output to use courier, a fixed-width font Helps to align display –Method setFont Can change font of most GUI components Takes a Font object –Font objects Initialized with –String name of font –int representing style ( Font.PLAIN, Font.BOLD, Font.ITALIC ) –int representing point size 36 output = new JTextArea( 6, 60 ); 37 output.setFont( 38 new Font( "Courier", Font.PLAIN, 12 ) );

 2000 Prentice Hall, Inc. All rights reserved. Outline import 1.1 Declare array a 2. init 2.1 GUI 2.2 Register event handler 1// Fig. 7.13: BinarySearch.java 2// Binary search of an array 3import java.awt.*; 4import java.awt.event.*; 5import javax.swing.*; 6import java.text.*; 7 8public class BinarySearch extends JApplet 9 implements ActionListener { 10 JLabel enterLabel, resultLabel; 11 JTextField enter, result; 12 JTextArea output; int a[]; 15 String display = ""; public void init() 18 { 19 Container c = getContentPane(); 20 c.setLayout( new FlowLayout() ); enterLabel = new JLabel( "Enter key" ); 23 c.add( enterLabel ); enter = new JTextField( 5 ); 26 enter.addActionListener( this ); 27 c.add( enter ); resultLabel = new JLabel( "Result" ); 30 c.add( resultLabel );

 2000 Prentice Hall, Inc. All rights reserved. Outline setFont 2.4 Create and initialize array 3. Event handler result = new JTextField( 22 ); 33 result.setEditable( false ); 34 c.add( result ); output = new JTextArea( 6, 60 ); 37 output.setFont( 38 new Font( "Courier", Font.PLAIN, 12 ) ); 39 c.add( output ); // create array and fill with even integers 0 to a = new int[ 15 ]; for ( int i = 0; i < a.length; i++ ) 45 a[ i ] = 2 * i; 46 } public void actionPerformed( ActionEvent e ) 50 { 51 String searchKey = e.getActionCommand(); // initialize display string for the new search 54 display = "Portions of array searched\n"; // perform the binary search 57 int element = 58 binarySearch( a, Integer.parseInt( searchKey ) ); output.setText( display );

 2000 Prentice Hall, Inc. All rights reserved. Outline binarySearch definition 4.1 Initialize subscripts if ( element != -1 ) 63 result.setText( 64 "Found value in element " + element ); 65 else 66 result.setText( "Value not found" ); 67 } // Binary search 70 public int binarySearch( int array[], int key ) 71 { 72 int low = 0; // low subscript 73 int high = array.length - 1; // high subscript 74 int middle; // middle subscript while ( low <= high ) { 77 middle = ( low + high ) / 2; // The following line is used to display the part 80 // of the array currently being manipulated during 81 // each iteration of the binary search loop. 82 buildOutput( low, middle, high ); if ( key == array[ middle ] ) // match 85 return middle; 86 else if ( key < array[ middle ] ) 87 high = middle - 1; // search low end of array 88 else 89 low = middle + 1; // search high end of array 90 } Middle element is the average of the high and low elements. If key equal to middle element, return it. If less or greater, adjust high or low.

 2000 Prentice Hall, Inc. All rights reserved. Outline buildOutput definition return -1; // searchKey not found 93 } // Build one row of output showing the current 96 // part of the array being processed. 97 void buildOutput( int low, int mid, int high ) 98 { 99 DecimalFormat twoDigits = new DecimalFormat( "00" ); for ( int i = 0; i < a.length; i++ ) { 102 if ( i high ) 103 display += " "; 104 else if ( i == mid ) // mark middle element in output 105 display += twoDigits.format( a[ i ] ) + "* "; 106 else 107 display += twoDigits.format( a[ i ] ) + " "; 108 } display += "\n"; 111 } 112} Loop through and display part of array being searched. If not being searched, display a blank. Mark middle element with *

 2000 Prentice Hall, Inc. All rights reserved. Outline 34 Program Output

 2000 Prentice Hall, Inc. All rights reserved Multiple-Subscripted Arrays Multiple-Subscripted Arrays –Represent tables Arranged by m rows and n columns (m by n array) Can have more than two subscripts –Java does not support multiple subscripts directly Creates an array with arrays as its elements Array of arrays Row 0 Row 1 Row 2 Column 0Column 1Column 2Column 3 a[0][0] a[1][0] a[2][0] a[0][1] a[1][1] a[2][1] a[0][2] a[1][2] a[2][2] a[0][3] a[1][3] a[2][3] Row subscript Array name Column subscript

 2000 Prentice Hall, Inc. All rights reserved Multiple-Subscripted Arrays Declaration –Fixed rows and columns arrayType arrayName [][] = new arrayType [ numRows ][ numColumns ]; int b[][] = new int[ 3 ][ 3 ]; –Initializer lists arrayType arrayName [][] = { { row1 sub-list }, { row2 sub-list },... }; int b[][] = { { 1, 2 }, { 3, 4 } }; 12 34

 2000 Prentice Hall, Inc. All rights reserved Multiple-Subscripted Arrays Rows with different columns –Each row element is an array int b[][]; b = new int[ 2 ][ ]; // allocate rows b[ 0 ] = new int[ 5 ]; // allocate columns for // row 0 b[ 1 ] = new int[ 3 ]; // allocate columns for // row 1 –Notice how b[ 0 ] is initialized as a new int array To pass the entire row to a function, pass b[ 0 ] –b.length - number of rows –b[ i ].length - number of columns in row i

 2000 Prentice Hall, Inc. All rights reserved. Outline init 1.1 GUI 1.2 Initialize double- scripted arrays 1// Fig. 7.15: InitArray.java 2// Initializing multidimensional arrays 3import java.awt.Container; 4import javax.swing.*; 5 6public class InitArray extends JApplet { 7 JTextArea outputArea; 8 9 // paint the applet 10 public void init() 11 { 12 outputArea = new JTextArea(); 13 Container c = getContentPane(); 14 c.add( outputArea ); int array1[][] = { { 1, 2, 3 }, { 4, 5, 6 } }; 17 int array2[][] = { { 1, 2 }, { 3 }, { 4, 5, 6 } }; outputArea.setText( "Values in array1 by row are\n" ); 20 buildOutput( array1 ); outputArea.append( "\nValues in array2 by row are\n" ); 23 buildOutput( array2 ); 24 } Notice how the double scripted arrays are declared. Each row is inside braces.

 2000 Prentice Hall, Inc. All rights reserved. Outline buildOutput definition Program Output public void buildOutput( int a[][] ) 27 { 28 for ( int i = 0; i < a.length; i++ ) { for ( int j = 0; j < a[ i ].length; j++ ) 31 outputArea.append( a[ i ][ j ] + " " ); outputArea.append( "\n" ); 34 } 35 } 36}

 2000 Prentice Hall, Inc. All rights reserved Multiple-Subscripted Arrays Upcoming applet –Use double scripted array for student grades Row - student Column - grades on test –Print average, high, low

 2000 Prentice Hall, Inc. All rights reserved. Outline Initialize double scripted array 2. init 2.1 GUI 1// Fig. 7.16: DoubleArray.java 2// Double-subscripted array example 3import java.awt.*; 4import javax.swing.*; 5 6public class DoubleArray extends JApplet { 7 int grades[][] = { { 77, 68, 86, 73 }, 8 { 96, 87, 89, 81 }, 9 { 70, 90, 86, 81 } }; int students, exams; 12 String output; 13 JTextArea outputArea; // initialize instance variables 16 public void init() 17 { 18 students = grades.length; 19 exams = grades[ 0 ].length; outputArea = new JTextArea(); 22 Container c = getContentPane(); 23 c.add( outputArea ); // build the output string 26 output = "The array is:\n"; 27 buildString();

 2000 Prentice Hall, Inc. All rights reserved. Outline Create output 2.3 setFont 3. minimum definition output += "\n\nLowest grade: " + minimum() + 30 "\nHighest grade: " + maximum() + "\n"; for ( int i = 0; i < students; i++ ) 33 output += "\nAverage for student " + i + " is " average( grades[ i ] ); outputArea.setFont( 37 new Font( "Courier", Font.PLAIN, 12 ) ); 38 outputArea.setText( output ); 39 } // find the minimum grade public int minimum() 43 { 44 int lowGrade = 100; for ( int i = 0; i < students; i++ ) 47 for ( int j = 0; j < exams; j++ ) 48 if ( grades[ i ][ j ] < lowGrade ) 49 lowGrade = grades[ i ][ j ]; return lowGrade; 52 } 53 Look through entire array. If a grade is lower than lowGrade, lowGrade is set to it. Pass a row (a student) to method average

 2000 Prentice Hall, Inc. All rights reserved. Outline maximum definition 5. average definition 54 // find the maximum grade public int maximum() 56 { 57 int highGrade = 0; for ( int i = 0; i < students; i++ ) 60 for ( int j = 0; j < exams; j++ ) 61 if ( grades[ i ][ j ] > highGrade ) 62 highGrade = grades[ i ][ j ]; return highGrade; 65 } // determine the average grade for a particular 68 // student (or set of grades) 69 public double average( int setOfGrades[] ) 70 { 71 int total = 0; for ( int i = 0; i < setOfGrades.length; i++ ) 74 total += setOfGrades[ i ]; return ( double ) total / setOfGrades.length; 77 } 78 Like minimum, searches through array, sets highGrade. Rows of the double scripted array are actually arrays containing the grades.

 2000 Prentice Hall, Inc. All rights reserved. Outline buildString definition 79 // build output string 80 public void buildString() 81 { 82 output += " "; // used to align column heads for ( int i = 0; i < exams; i++ ) 85 output += "[" + i + "] "; for ( int i = 0; i < students; i++ ) { 88 output += "\ngrades[" + i + "] "; for ( int j = 0; j < exams; j++ ) 91 output += grades[ i ][ j ] + " "; 92 } 93 } 94}