 1992-2007 Pearson Education, Inc. All rights reserved. 1 7 7 Arrays.

Slides:



Advertisements
Similar presentations
Arrays.
Advertisements

 2006 Pearson Education, Inc. All rights reserved Arrays.
 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.
5 5 Arrays. OBJECTIVES In this lecture we will learn:  Case switch  To use the array data structure to represent a set of related data items.  To declare.
 2003 Prentice Hall, Inc. All rights reserved Introduction Arrays –Structures of related data items –Static entity (same size throughout program)
Introduction to Computers and Programming Lecture 16: Arrays (cont) Professor: Evan Korth New York University.
Arrays Chapter 6.
 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.
 2005 Pearson Education, Inc. All rights reserved Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
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. Modified for use with this course. Introduction to Arrays Introduction to Computers and Programming in.
C++ for Engineers and Scientists Third Edition
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays and Vectors.
 Pearson Education, Inc. All rights reserved Arrays.
1 JavaScript/Jscript: Arrays. 2 Introduction Arrays –Data structures consisting of related data items (collections of data items) JavaScript arrays are.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
 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.
 2006 Pearson Education, Inc. All rights reserved Arrays.
CHAPTER 07 Arrays and Vectors (part I). OBJECTIVES 2 In this part you will learn:  To use the array data structure to represent a set of related data.
Arrays Chapter 7. 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores : Inspecting.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
 2005 Pearson Education, Inc. All rights reserved. 1 Arrays Part 4.
 Pearson Education, Inc. All rights reserved Arrays.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
 2005 Pearson Education, Inc. All rights reserved. 1 Arrays.
 Pearson Education, Inc. All rights reserved Arrays.
Chapter 7 Arrays. A 12-element array Declaring and Creating Arrays Arrays are objects that occupy memory Created dynamically with keyword new int c[]
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
 2005 Pearson Education, Inc. All rights reserved Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
1 Arrays and Vectors Chapter 7 Arrays and Vectors Chapter 7.
 Pearson Education, Inc. All rights reserved Arrays.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays Chapter 7. 2 Declaring and Creating Arrays Recall that an array is a collection of elements all of the _____________ Array objects in Java must.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
 Pearson Education, Inc. All rights reserved Passing Arrays to Methods To pass array argument to a method – Specify array name without.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
 2005 Pearson Education, Inc. All rights reserved Arrays.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Chapter 9 Introduction to Arrays Fundamentals of Java.
 2008 Pearson Education, Inc. All rights reserved Arrays and Vectors.
 2006 Pearson Education, Inc. All rights reserved Arrays and Vectors.
A DVANCED P ROGRAMMING C HAPTER 8: A RRAYS Dr Shahriar Bijani Spring 2016.
Lecture 4: Chapter 7 - Arrays Outline Declaring and Creating Arrays Examples Using Arrays References and Reference Parameters Passing Arrays to Methods.
Arrays Chapter 7.
© 2016 Pearson Education, Ltd. All rights reserved.
8 Arrays.
Java How to Program, Late Objects Version, 10/e
7 Arrays.
7 Arrays.
7 Arrays.
7 Arrays.
Object Oriented Programming in java
MSIS 655 Advanced Business Applications Programming
Arrays Chapter 7.
7 Arrays.
2 Array of Objects.
Presentation transcript:

 Pearson Education, Inc. All rights reserved Arrays

 Pearson Education, Inc. All rights reserved. 2 OBJECTIVES In this chapter you will learn:  What arrays are.  To use arrays to store data in and retrieve data from lists and tables of values.  To declare an array, initialize an array and refer to individual elements of an array.  To use the enhanced for statement to iterate through arrays.  To pass arrays to methods.  To declare and manipulate multidimensional arrays.  To write methods that use variable-length argument lists.  To read command-line arguments into a program.

 Pearson Education, Inc. All rights reserved Introduction 7.2 Arrays 7.3 Declaring and Creating Arrays 7.4 Examples Using Arrays 7.5 Case Study: Card Shuffling and Dealing Simulation 7.6 Enhanced for Statement 7.7 Passing Arrays to Methods 7.8 Case Study: Class GradeBook Using an Array to Store Grades 7.9 Multidimensional Arrays 7.10 Case Study: Class GradeBook Using a Two-Dimensional Array 7.11 Variable-Length Argument Lists 7.12 Using Command-Line Arguments 7.13 (Optional) GUI and Graphics Case Study: Drawing Arcs 7.14 (Optional) Software Engineering Case Study: Collaboration Among Objects 7.15 Wrap-Up

 Pearson Education, Inc. All rights reserved Introduction Arrays – Data structures – Related data items of same type – Remain same size once created Fixed-length entries

 Pearson Education, Inc. All rights reserved Arrays Array – Group of variables Have same type – Reference type

 Pearson Education, Inc. All rights reserved. 6 Fig. 7.1 | A 12-element array.

 Pearson Education, Inc. All rights reserved Arrays (Cont.) Index – Also called subscript – Position number in square brackets – Must be positive integer or integer expression – First element has index zero a = 5; b = 6; c[ a + b ] += 2; Adds 2 to c[ 11 ]

 Pearson Education, Inc. All rights reserved. 8 Common Programming Error 7.1 Using a value of type long as an array index results in a compilation error. An index must be an int value or a value of a type that can be promoted to int—namely, byte, short or char, but not long.

 Pearson Education, Inc. All rights reserved Arrays (Cont.) Examine array c – c is the array name – c.length accesses array c ’s length – c has 12 elements ( c[0], c[1], … c[11] ) The value of c[0] is –45

 Pearson Education, Inc. All rights reserved Declaring and Creating Arrays Declaring and Creating arrays – Arrays are objects that occupy memory – Created dynamically with keyword new int c[] = new int[ 12 ]; – Equivalent to int c[]; // declare array variable c = new int[ 12 ]; // create array the [] following c indicate that – c is a variable refering to an array – or a reference variabe in the assignment statement c refers to a 12 integer element array – default initial values 0 for numerial variables: false for boolean null for reference types

 Pearson Education, Inc. All rights reserved Declaring and Creating Arrays We can create arrays of objects too String b[] = new String[ 100 ]; this is possible double [] array1, array2; equivalent to double array1{]; double array2[]; or double[] array1; double[] array2;

 Pearson Education, Inc. All rights reserved. 12 Common Programming Error 7.3 Declaring multiple array variables in a single declaration can lead to subtle errors. Consider the declaration int[] a, b, c;. If a, b and c should be declared as array variables, then this declaration is correct—placing square brackets directly following the type indicates that all the identifiers in the declaration are array variables. However, if only a is intended to be an array variable, and b and c are intended to be individual int variables, then this declaration is incorrect—the declaration int a[], b, c; would achieve the desired result.

 Pearson Education, Inc. All rights reserved Examples Using Arrays Declaring arrays Creating arrays Initializing arrays Manipulating array elements

 Pearson Education, Inc. All rights reserved Examples Using Arrays Creating and initializing an array – Declare array – Create array – Initialize array elements

 Pearson Education, Inc. All rights reserved. 15 Outline InitArray.java Line 8 Declare array as an array of ints Line 10 Create 10 ints for array; each int is initialized to 0 by default Line 15 array.length returns length of array Line 16 array[counter] returns int associated with index in array Program output Declare array as an array of int s Create 10 int s for array ; each int is initialized to 0 by default array.length returns length of array array[counter] returns int associated with index in array Each int is initialized to 0 by default

 Pearson Education, Inc. All rights reserved // Fig. 7.2: InitArray.java 2 // Creating an array. 3 4 public class InitArray 5 { 6 public static void main( String args[] ) 7 { 8 int array[]; // declare array named array 9 10 array = new int[ 10 ]; // create the space for array System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings // output each array element's value 15 for ( int counter = 0; counter < array.length; counter++ ) 16 System.out.printf( "%5d%8d\n", counter, array[ counter ] ); 17 } // end main 18 } // end class InitArray

 Pearson Education, Inc. All rights reserved Examples Using Arrays (Cont.) Using an array initializer – Use initializer list Items enclosed in braces ( {} ) Items in list separated by commas int n[] = { 10, 20, 30, 40, 50 }; – Creates a five-element array – Index values of 0, 1, 2, 3, 4 – Do not need keyword new

 Pearson Education, Inc. All rights reserved. 18 Outline InitArray.java Line 9 Declare array as an array of ints Line 9 Compiler uses initializer list to allocate array Program output Declare array as an array of int s Compiler uses initializer list to allocate array

 Pearson Education, Inc. All rights reserved // Fig. 7.3: InitArray.java 2 // Initializing the elements of an array with an array initializer. 3 4 public class InitArray { 6 public static void main( String args[] ) 7 { 8 // initializer list specifies the value for eachelement 9 int array[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; 10 11System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings // output each array element's value 14 for ( int counter = 0; counter < array.length; counter++ ) 15 System.out.printf( "%5d%8d\n", counter, array[ counter ] ); 16 } // end main 17 } // end class InitArray

 Pearson Education, Inc. All rights reserved. 20 int array[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; System.out.printf( "%s%8s\n", "Index", "Value" ); // output each array element's value for ( int counter = 0; counter < array.length; counter++ ) System.out.printf( "%5d%8d\n", counter, array[ counter ] );

 Pearson Education, Inc. All rights reserved Examples Using Arrays (Cont.) Calculating a value to store in each array element – Initialize elements of 10-element array to even integers

 Pearson Education, Inc. All rights reserved. 22 Outline InitArray.java Line 8 Declare constant variable Line 9 Declare and create array that contains 10 ints Line 13 Use array index to assign array Program output

 Pearson Education, Inc. All rights reserved. 23 final int ARRAY_LENGTH = 10; // declare constant int array[] = new int[ ARRAY_LENGTH ]; // create array // calculate value for each array element for ( int counter = 0; counter < array.length; counter++ ) array[ counter ] = * counter; System.out.printf( "%s%8s\n", "Index", "Value" ); // output each array element's value for ( int counter = 0; counter < array.length; counter++ ) System.out.printf( "%5d%8d\n", counter, array[ counter ] );

 Pearson Education, Inc. All rights reserved. 24 Good Programming Practice 7.2Good Programming Practice 7.2 Constant variables also are called named constants or read-only variables. Such variables often make programs more readable than programs that use literal values (e.g., 10)—a named constant such as ARRAY_LENGTH clearly indicates its purpose, whereas a literal value could have different meanings based on the context in which it is used.

 Pearson Education, Inc. All rights reserved. 25 Getting the elements of an array from The user

 Pearson Education, Inc. All rights reserved. 26 Scanner input = new Scanner(System.in); final int ARRAY_LENGTH = 10; // declare constant int array[] = new int[ ARRAY_LENGTH ]; // create array // get th value for each array element from user for ( int counter = 0; counter < array.length; counter++ ) { System.out.print(“Enter ” + counter + “th element:”); array[ counter ] =input.nextInt(); } // rest of the program is th same

 Pearson Education, Inc. All rights reserved Examples Using Arrays (Cont.) Summing the elements of an array Array elements can represent a series of values We can sum these values

 Pearson Education, Inc. All rights reserved. 28 Common Programming Error 7.4 Assigning a value to a constant after the variable has been initialized is a compilation error.

 Pearson Education, Inc. All rights reserved. 29 Common Programming Error 7.5 Attempting to use a constant before it is initialized is a compilation error.

 Pearson Education, Inc. All rights reserved Examples Using Arrays (Cont.) Summing the elements of an array – Array elements can represent a series of values We can sum these values

 Pearson Education, Inc. All rights reserved. 31 Outline SumArray.java Line 8 Declare array with initializer list Lines Sum all array values Program output

 Pearson Education, Inc. All rights reserved. 32 int array[] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 }; int total = 0; // add each element's value to total for ( int counter = 0; counter < array.length; counter++ ) total += array[ counter ]; System.out.printf( "Total of array elements: %d\n", total );

 Pearson Education, Inc. All rights reserved Examples Using Arrays (Cont.) Using bar charts to display array data graphically – Present data in graphical manner E.g., bar chart – Examine the distribution of grades

 Pearson Education, Inc. All rights reserved. 34 Outline BarChart.java (1 of 2) Line 8 Declare array with initializer list Line 19 Use the 0 flag to display one- digit grade with a leading 0 Lines For each array element, print associated number of asterisks Declare array with initializer list For each array element, print associated number of asterisks Use the 0 flag to display one- digit grade with a leading 0

 Pearson Education, Inc. All rights reserved. 35 Outline BarChart.java (2 of 2) Program output

 Pearson Education, Inc. All rights reserved Examples Using Arrays (Cont.) Using the elements of an array as counters – Use a series of counter variables to summarize data

 Pearson Education, Inc. All rights reserved. 37 Outline RollDie.java Line 10 Declare frequency as array of 7 ints Lines Generate 6000 random integers in range 1-6 Line 14 Increment frequency values at index associated with random number Program output

 Pearson Education, Inc. All rights reserved. 38 import java.util.Random; Random randomNumbers = new Random(); // random number generator int frequency[] = new int[ 7 ]; // array of frequency counters // roll die 6000 times; use die value as frequency index for ( int roll = 1; roll <= 6000; roll++ ) ++frequency[ 1 + randomNumbers.nextInt( 6 ) ]; System.out.printf( "%s%10s\n", "Face", "Frequency" ); // output each array element's value for ( int face = 1; face < frequency.length; face++ ) System.out.printf( "%4d%10d\n", face, frequency[ face ] );

 Pearson Education, Inc. All rights reserved Examples Using Arrays (Cont.) Using arrays to analyze survey results – 40 students rate the quality of food 1-10 Rating scale: 1 means awful, 10 means excellent – Place 40 responses in array of integers – Summarize results

 Pearson Education, Inc. All rights reserved. 40 Outline StudentPoll.java (1 of 2) Lines 9-11 Declare responses as array to store 40 responses Line 12 Declare frequency as array of 11 int and ignore the first element Lines For each response, increment frequency values at index associated with that response Declare responses as array to store 40 responses Declare frequency as array of 11 int and ignore the first element For each response, increment frequency values at index associated with that response

 Pearson Education, Inc. All rights reserved. 41 Outline StudentPoll.java (2 of 2) Program output

 Pearson Education, Inc. All rights reserved. 42 Error-Prevention Tip 7.1 An exception indicates that an error has occurred in a program. A programmer often 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, an ArrayIndexOutOfBoundsException occurs. Exception handling is discussed in Chapter 13.

 Pearson Education, Inc. All rights reserved. 43 Error-Prevention Tip 7.2 When writing code to loop through an array, ensure that the array index is always greater than or equal to 0 and less than the length of the array. The loop-continuation condition should prevent the accessing of elements outside this range.

 Pearson Education, Inc. All rights reserved Case Study: Card Shuffling and Dealing Simulation Program simulates card shuffling and dealing – Use random number generation – Use an array of reference type elements to represent cards – Three classes Card – Represents a playing card DeckOfCards – Represents a deck of 52 playing cards DeckOfCardsTest – Demonstrates card shuffling and dealing

 Pearson Education, Inc. All rights reserved. 45 Outline Card.java Lines Return the string representation of a card

 Pearson Education, Inc. All rights reserved. 46 Outline Card.java Lines 17-20

 Pearson Education, Inc. All rights reserved. 47 Outline DeckOfCards.java (1 of 2) Line 7 Line 9 Lines Line 17 Lines Declare deck as array to store Card objects Constant NUMBER_OF_CARDS indicates the number of Cards in the deck Declare and initialize faces with String s that represent the face of card Declare and initialize suits with String s that represent the suit of card Fill the deck array with Card s

 Pearson Education, Inc. All rights reserved. 48 Outline DeckOfCards.java (2 of 2) Lines Line 52 Swap current Card with randomly selected Card Determine whether deck is empty

 Pearson Education, Inc. All rights reserved. 49 Outline DeckOfCardsTest.java (1 of 2)

 Pearson Education, Inc. All rights reserved. 50 Outline DeckOfCardsTest.java (2 of 2)

 Pearson Education, Inc. All rights reserved Enhanced for Statement Enhanced for statement – Iterates through elements of an array or a collection without using a counter – Syntax for ( parameter : arrayName ) statement

 Pearson Education, Inc. All rights reserved. 52 Outline EnhancedForTest.java

 Pearson Education, Inc. All rights reserved Enhanced for Statement (Cont.) int array[] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 }; int total = 0; // add each element's value to total for ( int number : array ) total += number; System.out.printf( "Total of array elements: %d\n", total );

 Pearson Education, Inc. All rights reserved Enhanced for Statement (Cont.) Lines are equivalent to for ( int counter = 0; counter < array.length; counter++ ) total += array[ counter ]; Usage – Can access array elements – Cannot modify array elements – Cannot access the counter indicating the index

 Pearson Education, Inc. All rights reserved Passing Arrays to Methods To pass array argument to a method – Specify array name without brackets Array hourlyTemperatures is declared as int hourlyTemperatures = new int[ 24 ]; The method call modifyArray( hourlyTemperatures ); Passes array hourlyTemperatures to method modifyArray

 Pearson Education, Inc. All rights reserved. 56 Outline PassArray.java (1 of 2) Line 9 Line 19 Declare 5 - int array with initializer list Pass entire array to method modifyArray

 Pearson Education, Inc. All rights reserved. 57 Outline PassArray.java (2 of 2) Line 30 Lines Lines Program output Pass array element array[3] to method modifyElement Method modifyArray manipulates the array directly Method modifyElement manipulates a primitive’s copy

 Pearson Education, Inc. All rights reserved Passing Arrays to Methods (Cont.) // Fig. 7.13: PassArray.java // Passing arrays and individual array elements to methods. public class PassArray { // main creates array and calls modifyArray and modifyElement public static void main( String args[] ) { int array[] = { 1, 2, 3, 4, 5 }; System.out.println( "Effects of passing reference to entire array:\n" + "The values of the original array are:" ); // output original array elements for ( int value : array ) System.out.printf( " %d", value );

 Pearson Education, Inc. All rights reserved Passing Arrays to Methods (Cont.) modifyArray( array ); // pass array reference System.out.println( "\n\nThe values of the modified array are:" ); // output modified array elements for ( int value : array ) System.out.printf( " %d", value ); System.out.printf( "\n\nEffects of passing array element value:\n" + "array[3] before modifyElement: %d\n", array[ 3 ] ); modifyElement( array[ 3 ] ); // attempt to modify array[ 3 ] System.out.printf( "array[3] after modifyElement: %d\n", array[ 3 ] ); } // end main

 Pearson Education, Inc. All rights reserved. 60 // multiply each element of an array by 2 public static void modifyArray( int array2[] ) { for ( int counter = 0; counter < array2.length; counter++ ) array2[ counter ] *= 2; } // end method modifyArray // multiply argument by 2 public static void modifyElement( int element ) { element *= 2; System.out.printf( "Value of element in modifyElement: %d\n", element ); } // end method modifyElement } // end class PassArray

 Pearson Education, Inc. All rights reserved. 61 Effects of passing reference to entire array: The values of the original array are: The values of the modified array are: Effects of passing array element value: array[3] before modifyElement: 8 Value of element in modifyElement: 16 array[3] after modifyElement: 8 output

 Pearson Education, Inc. All rights reserved Passing Arrays to Methods (Cont.) Notes on passing arguments to methods – Two ways to pass arguments to methods Pass-by-value – Copy of argument’s value is passed to called method – Every primitive type is passed-by-value Pass-by-reference – Caller gives called method direct access to caller’s data – Called method can manipulate this data – Improved performance over pass-by-value – Every object is passed-by-reference Arrays are objects Therefore, arrays are passed by reference

 Pearson Education, Inc. All rights reserved Passing Arrays to Methods (Cont.) public class PassValues { public static void main(String args[]) { int a = 5, b = 10; // printing before change System.out.printf(“a: %d b:%d\n”,a,b); change(a,b); // printing after change System.out.printf(“a: %d b:%d\n”,a,b); } // end of main

 Pearson Education, Inc. All rights reserved Passing Arrays to Methods (Cont.) public static void change(int x, int y) { int temp = x; x = y; y = temp; System.out.printf(“x: %d y:%d\n”,x,y); } // end of change method } // end of class PassValue

 Pearson Education, Inc. All rights reserved Passing Arrays to Methods (Cont.) public class PassReference { public static void main(String args[]) { MyInt a = new MyInt(5); MyInt b = new MyInt(10); // printing before change System.out.printf(“a: %d b:%d\n”,a.value,b.value); change(a,b); // printing after change System.out.printf(“a: %d b:%d\n”,a.value,b.value); } // end of main

 Pearson Education, Inc. All rights reserved Passing Arrays to Methods (Cont.) public static void change(MyInt x, MyInt y) { int temp = x.value; x.value = y.value; y.value = temp; System.out.printf(“x: %d y:%d\n”,x.value,y.value); } // end of change method } // end of class PassValue

 Pearson Education, Inc. All rights reserved Passing Arrays to Methods (Cont.) public class MyInt { public int value; public MyInt(int x) { value = x; } // end constructor } // end class MyInt /* in general avoid this do not declare value as a public get its value with getValue() method Here for illustration and simplicity declare value as public */

 Pearson Education, Inc. All rights reserved. 68 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 consume considerable storage for the copies of the arrays.

 Pearson Education, Inc. All rights reserved. 69 A generic array class Develop a gneric array class called MyArray including many methods for – geting arrays – pringting the array – calculating sum, average,standard deviation, minimum, maximum,.. – modifying arrays: multiply by two store in another array – finding distinct values of arrays – sorting, searching in arrays – fining union, intersetion of two arrays

 Pearson Education, Inc. All rights reserved. 70 A generic array class public class MyArray { private int[] myArray; // constructor public MyArray(int[] theArray) { myArray = theArray; // initialized elsewhere in another class // just pass the reference }

 Pearson Education, Inc. All rights reserved. 71 A generic array class public int maximum() { int max = myArray[0]; for(int e : myArray) // loop over elements if(e > max) // here e represent the element max = e; return max; }

 Pearson Education, Inc. All rights reserved. 72 A generic array class public int maxPosition() { int max = myArray[0]; int position = 0; for(int i=0;i < myArray.length;i++) // loop over index if(myArray[i] > max) // i is the index of the array { max = myArray[i]; position = i; } return position; }

 Pearson Education, Inc. All rights reserved. 73 A generic array class this methods take an array and return its maximum or position of the maximum value as an intger primitive variable How to call such methods in another class int[] a = {1,2,3,4,5}; // create a myA type object sening array a to its constructor MyArray myA = new MyArray(a); // initilize myA // call the maximum method of over myA int maxOfa = myA.maximum(); int posMax = myA.maxPosition();

 Pearson Education, Inc. All rights reserved. 74 A generic array class A procedural approach for such mehods is declaring each method in the same class as arrays are defined

 Pearson Education, Inc. All rights reserved. 75 public class ArrayMetodsProcedural { public static void main(String args[]) { int[] a = { }; int maxOfA = maximum(a); int posOfA = maxPosition(a); // print these } // end of main method

 Pearson Education, Inc. All rights reserved. 76 public static int maximum( int[] myArray) { int max = myArray[0]; for(int i : myArray) // loop over elements if(i > max) // here i represent the element max = i; return max; } // end of maximum // write the maxPosition method as an exercise } end of class arrayMethodsProcedural

 Pearson Education, Inc. All rights reserved. 77 A generic array class Methods may also return arrays as rferences – what if thee are more then one maximum value in an array how can the possition of each can be returned – e.g. a = {1,2,5,1,5} – maximum value is 5 its positions are 2 and 4 – so an array returning positions should be {2,4} Other examples – copying an array – finding unions, intersection of arrays – inverting an array – reversing its elements – Searching arrays

 Pearson Education, Inc. All rights reserved. 78 A generic array class Example inverting an array elements a = { } ainv = { } a method that takes as the original array and modifys the original array a method that takes the original array and returns a new invered array a method that takes the original array and another array as parameters and modify the second array a method that creates a MyArray objcet and initialize it with the inverted array returning the reference of the MyArray objcet

 Pearson Education, Inc. All rights reserved. 79 A generic array class public static void invert1(int[] array) { int temp, n = array.length; for( int i = 0 ; i <= n/2-1 ; i++ ) { temp = array[i]; array[i] = array[n-i-1] = ; array[n-i-1] = temp; } // end of for loop } // end of method

 Pearson Education, Inc. All rights reserved. 80 A generic array class public static int[] invert2(int[] array ) { int n = array.length; int[] invArray = new int[n]; for( int i = 0 ; i < n ; i++ ) invArray[i] = array[n-i-1]; return invArray; } // end of method

 Pearson Education, Inc. All rights reserved. 81 A generic array class public static void invert3(int[] array,int[] invArray ) { int n = array.length; invArray = new int[n]; for( int i = 0 ; i < n ; i++ ) invArray[i] = array[n-i-1]; } // end of method

 Pearson Education, Inc. All rights reserved. 82 A generic array class public class InvertStatic { public static void main(String args[]) [ int[] a = { }; invert1(a); // display array a it is inverted int b[] = new int[a.length]; // same lenght as array a invert3(a,b); // display a and b // b is the original array int[] c = invert2(a); // print c } // end of main method

 Pearson Education, Inc. All rights reserved. 83 non static versions the non static versions of the invert1, invert2 and invert3 methods are called over objcets say lets create MyArray type objects and call these methods on these objcets

 Pearson Education, Inc. All rights reserved. 84 public class MyArray { int[] myArray; public MyArray(int[] myArray) { this.myArray = myArray; }

 Pearson Education, Inc. All rights reserved. 85 // invert1 has no parameter and retrurn no parameter // takes the instance variable myArray and inverts it public void invert1() { int temp, n = myArray.length; for( int i = 0 ; i <= n/2-1 ; i++ ) { temp = myArray[i]; myArray[i] = myArray[n-i-1]; myArray[n-i-1] = temp; } // end of for loop } // end of method

 Pearson Education, Inc. All rights reserved. 86 calling invert1 from another class public class InvertTest {ddyt public static void main(String args[]) { int[] a = {1,4,2,5,9}; MyArray myA = new MyArray(a); myA.invert1(); // display array a it is inverted }

 Pearson Education, Inc. All rights reserved. 87 other methods of the MyArray class public class MyArray { int[] myArray; public MyArray(int[] myArray) { this.myArray = myArray; } public void invert1() {..... }

 Pearson Education, Inc. All rights reserved. 88 public int[] invert2() { int n = myArray.length; int[] invArray = new int[n]; for( int i = 0 ; i < n ; i++ ) invArray[i] = myArray[n-i-1]; return invArray; } // end of method

 Pearson Education, Inc. All rights reserved. 89 how to call invert2 from main public class InvertTest { public static void main(String args[]) { int[] a = {1,4,2,5,9}; MyArray myA = new MyArray(a); int[] b = myA.invert2(); // display array b it is inverted version of array a } // end of main } // end of calss InvertTest

 Pearson Education, Inc. All rights reserved. 90 finding the position of maximum add another method to the MyArray class so that it will return the indesis of the maximum element in an array there may be more then one index so the return type should be an array whose length is equal or shorther then the original array

 Pearson Education, Inc. All rights reserved. 91 public class MyArray { int[] myArray; // constructor and other methods

 Pearson Education, Inc. All rights reserved. 92 public int[] maxPosition(); { int[] postemp = new int[myArray.length] int max=myArray[0],nPos = -1; for(int i=0;i<myArray.length;i++) { if(myArray[i] > max) { max = myArray[i]; nPos = 0; postemp[nPos] = i; } else if (myArray[i] == max) { nPos++; postemp[nPos] = i; }

 Pearson Education, Inc. All rights reserved. 93 int[] positions = new int[nPos+1]; // copy the temorary array to the position array for(int i = 0;i < positions.lentgth;i++) positions[i] = postemp[i]; return positions; } // end of method

 Pearson Education, Inc. All rights reserved. 94 Searching in an array Linear search Add as a method to MyArray class Take the input a key an integer to be searched in the instance variable of MyArray class if found return the possition of the key if not fournd return -1

 Pearson Education, Inc. All rights reserved. 95 public int linearSearch(int key) { // loop through array sequentially for (int i = 0 ; i < myArray.length ; i++ ) if ( myArray[i] == key ) return i; // return index of integer return -1; // integer not found in array } // end of method

 Pearson Education, Inc. All rights reserved. 96 Test class for linear search import java.util.Scanner public class LinearSearchTest { public static void main(String args[]) { int[] a = {1,4,2,5,9}; MyArray myA = new MyArray(a); // get a key from the user; Scanner input = new Scanner(System.in); System.out.print(“Enter the key:”); int searchKey = input.nextInt(); // search the key in the array int searchRes = myA.linearSearch(searchKey); // display search results } // end of main } // end class

 Pearson Education, Inc. All rights reserved. 97 Exercise This version of the linear search method is restricted If the search key occors more then one possition in the array all of these should be returned – As an array of possitions – a = {2,4,2,5,2} – key =2 then – Return {0,2,4} possition array – key =7 – Return {-1} key not fournd

 Pearson Education, Inc. All rights reserved Case Study: Class GradeBook Using an Array to Store Grades Further evolve class GradeBook Class GradeBook – Represents a grade book that stores and analyzes grades – Does not maintain individual grade values – Repeat calculations require reentering the same grades Can be solved by storing grades in an array

 Pearson Education, Inc. All rights reserved. 99 Outline GradeBook.java (1 of 5) Line 7 Line 13 Declare array grades to store individual grades Assign the array’s reference to instance variable grades

 Pearson Education, Inc. All rights reserved. 100 Outline GradeBook.java (2 of 5)

 Pearson Education, Inc. All rights reserved. 101 Outline GradeBook.java (3 of 5) Lines Lines Loop through grades to find the lowest grade Loop through grades to find the highest grade

 Pearson Education, Inc. All rights reserved. 102 Outline GradeBook.java (4 of 5) Lines Lines Loop through grades to sum grades for one student Loop through grades to calculate frequency

 Pearson Education, Inc. All rights reserved. 103 Outline GradeBook.java (5 of 5) Lines Loop through grades to display each grade

 Pearson Education, Inc. All rights reserved. 104 Software Engineering Observation 7.1 A test harness (or test application) is responsible for creating an object of the class being tested and providing it with data. This data could come from any of several sources. Test data can be placed directly into an array with an array initializer, it can come from the user at the keyboard, it can come from a file (as you will see in Chapter 14), or it can come from a network (as you will see in Chapter 24). After passing this data to the class's constructor to instantiate the object, the test harness should call upon the object to test its methods and manipulate its data. Gathering data in the test harness like this allows the class to manipulate data from several sources.

 Pearson Education, Inc. All rights reserved. 105 Outline GradeBookTest.java (1 of 2) Line 10 Line 13 Declare and initialize gradesArray with 10 elements Pass gradesArray to GradeBook constructor

 Pearson Education, Inc. All rights reserved. 106 Outline GradeBookTest.java (2 of 2) Program output

 Pearson Education, Inc. All rights reserved Multidimensional Arrays public class copyArrayTest { public static void main(....) { int[] a = {1,2,3}; int [] b = copyArray(a); // print... } // end of main public static int[] copyArray(int a[]) { int[] b = new int[a.length]; for(int i = 0 ; i < a.length ; i++) b[i] = a[i]; return b; } // end of method } // end of class

 Pearson Education, Inc. All rights reserved Multidimensional Arrays Multidimensional arrays – Tables with rows and columns Two-dimensional array m-by-n array

 Pearson Education, Inc. All rights reserved. 109 Fig | Two-dimensional array with three rows and four columns.

 Pearson Education, Inc. All rights reserved Multidimensional Arrays (Cont.) Arrays of one-dimensional array – Declaring two-dimensional array b[2][2] int b[][] = { { 1, 2 }, { 3, 4 } }; – 1 and 2 initialize b[0][0] and b[0][1] – 3 and 4 initialize b[1][0] and b[1][1] int b[][] = { { 1, 2 }, { 3, 4, 5 } }; – row 0 contains elements 1 and 2 – row 1 contains elements 3, 4 and 5

 Pearson Education, Inc. All rights reserved Multidimensional Arrays (Cont.) Two-dimensional arrays with rows of different lengths – Lengths of rows in array are not required to be the same E.g., int b[][] = { { 1, 2 }, { 3, 4, 5 } };

 Pearson Education, Inc. All rights reserved Multidimensional Arrays (Cont.) Creating two-dimensional arrays with array- creation expressions – 3 -by- 4 array int b[][]; b = new int[ 3 ][ 4 ]; – Rows can have different number of columns 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

 Pearson Education, Inc. All rights reserved. 113 Outline InitArray.java (1 of 2) Line 9 Line 10

 Pearson Education, Inc. All rights reserved. 114 Outline InitArray.java (2 of 2) Line 26 Line 27 Program output

 Pearson Education, Inc. All rights reserved Multidimensional Arrays (Cont.) Common multidimensional-array manipulations performed with for statements – Many common array manipulations use for statements E.g., for ( int column = 0; column < a[ 2 ].length; column++ ) a[ 2 ][ column ] = 0;

 Pearson Education, Inc. All rights reserved. 116 public class My2DimArray { int[][] twoDimArray; // constructor public My2DimArray(int[][] newArray) { twoDimArray = newArray; }

 Pearson Education, Inc. All rights reserved. 117 public int[] rowSum() { int sum; int n = twoDimArray.length; int[] sumOfRaws = new int [n]; for ( int i = 0 ; i < n ; i++ ) { sum = 0; for(int j = 0 ; j < twoDimArray[i].length ; j++ ) sum += twoDimArray[i][j]; sumOfRaws[i] = sum; } // end of outer loop return sumOfRaws; } // end of method

 Pearson Education, Inc. All rights reserved. 118 Sum of columns if array is regtangular public int[] columnSum() { int sum; int n = twoDimArray[0].length; int m = twoDimArray.length; int[] sumOfColumns = new int [n]; for ( int i = 0 ; i < n ; i++ ) { sum = 0; for(int j = 0 ; j < m ; j++ ) sum += twoDimArray[j][i]; sumOfColumns[i] = sum; } // end of outer loop return sumOfRaws; } // end of method

 Pearson Education, Inc. All rights reserved. 119 Exercise Write a version of the column sum method for arrays whose number of elements in each row is not equal – They are not regtangular arrays E.g.: array = {{1,3}, {2,6,4}, {2} } sumOfRaws = {5,9,4}

 Pearson Education, Inc. All rights reserved. 120 public double[] rawAverages() { double[] ave = new double[twoDimArray.length]; for ( int i = 0 ; i < twoDimArray.length ; i++ ) ave[i] = getAverage(twoDimArray[i]); return ave; } public double getAverage(int a[]) { int sum = 0; for(int element : a ) sum += element; return (double) sum / a.length; }

 Pearson Education, Inc. All rights reserved. 121 public int[] columnMax() {... } public int[] rawMax() {... } Write their columnMin and rawMin versions as well

 Pearson Education, Inc. All rights reserved. 122 public int[][] transpose() { int n = twoDimArray.length; int m = twoDimArray[0].length; int[][] transpose = new int[m][n]; for(int i = 0;i < n;i++) for(int j = 0; j < m; j++ ) transpose[j][i] = twoDimArray[i][j]; return transpose; }

 Pearson Education, Inc. All rights reserved. 123 İsRectenge method is rectengle is a boolean method returns true or false Check whether the instance variable of the twoDimArray class is a regtengular array or not A two dimensional array to be a rectenge: length of each raw should be the same length of raw 0 = length of raw 1 length of raw 0 = length of raw 2 length of raw 0 = length of raw 3...

 Pearson Education, Inc. All rights reserved. 124 public boolean isRectenge() { boolean isRect = true; int n = twoDimArray.length; int m = twoDimArray[0].length; int i = 1; while(isRect && i < n) { isRect = (twoDimArray[i].length == m) && isRect; i++; } ret1urn isRect; }

 Pearson Education, Inc. All rights reserved. 125 Another version of the isRectange method public boolean isRectenge() { boolean isRect = true; int n = twoDimArray.length; int m = twoDimArray[0].length; int i = 0; while(isRect && ++i < n) isRect &= (twoDimArray[i].length == m); ret1urn isRect; }

 Pearson Education, Inc. All rights reserved. 126 Adding two matrisis a and b Part of the My2DimArray class Called on an objcet add the instance variable to the parameter of the method

 Pearson Education, Inc. All rights reserved. 127 public int[][] add(int b[][]) { int n = twDimArray.length; int m = twoDimArray[0].length; int[][] c = new[n][m]; for (int i =0 ; i < n ; i++) for (int j =0 ; j < m ; j++) c[i][j] = twoDimArray[i][j] + b[i][j]; return c; } // end of method

 Pearson Education, Inc. All rights reserved. 128 Exercise Write a method of the My2DimArray class for matrix multiplication – Check the dimensionality condition for the two matrisis and if the are not appropriate return a null reference

 Pearson Education, Inc. All rights reserved. 129 public class twoDimArrayTest { public static void main(String args[]) { int[][] a = {{2,4,6}, {5,1,7}}; TwoDimArray my2Dim = new TwoDimArray(a); }

 Pearson Education, Inc. All rights reserved. 130

 Pearson Education, Inc. All rights reserved Case Study: Class GradeBook Using a Two-Dimensional Array Class GradeBook – One-dimensional array Store student grades on a single exam – Two-dimensional array Store grades for a single student and for the class as a whole

 Pearson Education, Inc. All rights reserved. 132 Outline GradeBook.java (1 of 7) Line 7 Line 10 Declare two-dimensional array grades GradeBook constructor accepts a String and a two-dimensional array

 Pearson Education, Inc. All rights reserved. 133 Outline GradeBook.java (2 of 7)

 Pearson Education, Inc. All rights reserved. 134 Outline GradeBook.java (3 of 7) Lines Loop through rows of grades to find the lowest grade of any student

 Pearson Education, Inc. All rights reserved. 135 Outline GradeBook.java (4 of 7) Lines Lines Loop through rows of grades to find the highest grade of any student Calculate a particular student’s semester average

 Pearson Education, Inc. All rights reserved. 136 Outline GradeBook.java (5 of 7) Lines Calculate the distribution of all student grades

 Pearson Education, Inc. All rights reserved. 137 Outline GradeBook.java (6 of 7)

 Pearson Education, Inc. All rights reserved. 138 Outline GradeBook.java (7 of 7)

 Pearson Education, Inc. All rights reserved. 139 Outline GradeBookTest.java (1 of 2) Lines Declare gradesArray as 10- by-3 array Each row represents a student; each column represents an exam grade

 Pearson Education, Inc. All rights reserved. 140 Outline GradeBookTest.java (2 of 2) Program output

 Pearson Education, Inc. All rights reserved Variable-Length Argument Lists Variable-length argument lists – Unspecified number of arguments – Use ellipsis ( … ) in method’s parameter list Can occur only once in parameter list Must be placed at the end of parameter list – Array whose elements are all of the same type

 Pearson Education, Inc. All rights reserved. 142 Outline VarargsTest.java (1 of 2) Line 7 Lines Line 15

 Pearson Education, Inc. All rights reserved. 143 Outline VarargsTest.java (2 of 2) Line 29 Line 31 Line 33 Program output

 Pearson Education, Inc. All rights reserved. 144 Common Programming Error 7.6 Placing an ellipsis in the middle of a method parameter list is a syntax error. An ellipsis may be placed only at the end of the parameter list.

 Pearson Education, Inc. All rights reserved Using Command-Line Arguments Command-line arguments – Pass arguments from the command line String args[] – Appear after the class name in the java command java MyClass a b – Number of arguments passed in from command line args.length – First command-line argument args[ 0 ]

 Pearson Education, Inc. All rights reserved. 146 Outline InitArray.java (1 of 2) Line 6 Line 9 Line 16 Lines Lines Array args stores command- line arguments Check number of arguments passed in from the command line Obtain first command-line argument Obtain second and third command-line arguments Calculate the value for each array element based on command-line arguments

 Pearson Education, Inc. All rights reserved. 147 Outline InitArray.java (2 of 2) Program output Missing command-line arguments Three command-line arguments are 5, 0 and 4 Three command-line arguments are 10, 1 and 2