Chapter 9: Arrays

Preview:

DESCRIPTION

Chapter 9: Arrays. J ava P rogramming: From Problem Analysis to Program Design, Second Edition. Chapter Objectives. Learn about arrays. Explore how to declare and manipulate data into arrays. Understand the meaning of “array index out of bounds.” - PowerPoint PPT Presentation

Citation preview

Chapter 9: ArraysChapter 9: Arrays

JJavaava PProgramming:rogramming:

From Problem Analysis to Program From Problem Analysis to Program

Design,Design, Second EditionSecond Edition

2

Chapter Objectives

Learn about arrays. Explore how to declare and manipulate data into

arrays. Understand the meaning of “array index out of

bounds.” Become familiar with the restrictions on array

processing.

3

Chapter Objectives

Discover how to pass an array as a parameter to a method.

Discover how to manipulate data in a two-dimensional array.

Learn about multidimensional arrays.

4

MotivationWrite a program to read 5 numbers, find their sum and print them in reverse order.

import java.util.*; public class RevOrder{

static Scanner console = new Scanner(System.in); public static void main(String[] args){ int item0, item1, item2, item3, item4; int sum; System.out.println("Enter 5 numbers: "); item0=console.nextInt(); item1=console.nextInt(); item2=console.nextInt(); item3=console.nextInt(); item4=console.nextInt(); sum = item0+item1+item2+item3+item4; System.out.println("Sum = " + sum); System.out.print("Numbers is reverse = "); System.out.println(item4+" "+item3+" "+item2+" "+item1+" "+item0); }}

Enter 5 numbers:3 6 8 9 0Sum = 26Numbers is reverse = 0 9 8 6 3

5

Write a program to read 100 numbers, find their sum and print them in reverse

order

?????

Motivation

6

Note the following in the preceding program: 5 variables must be declared. All variables are of type int. Variables name (num0 num4);

Instead of having to use a large number of individual and unconnected variables, we can use a single data structure that combines them.

Motivation

7

In this chapter, we will examine: How to store collections of items and access

these items using one variable name given to the collection.

The data structure that lets you do all of theses things in java is called array.

Motivation

8

Array

A structured data type with a fixed number of components.

Every component is of the same type. Components are accessed using their relative

positions in the array.

9

Syntax to declare an array: dataType[ ] arrayName;

In java, an array is an object: It is a reference variable. To store data we must instantiate the array object

using new operator.

Syntax to instantiate an array object:arrayName = new dataType[intExp]

Where intExp = number of components in array >= 0

One-Dimensional Arrays

10

Declaration with instantiation: dataType[ ] arrayName = new dataType[intExp]

Declaring more than one array of the same type: dataType[ ] arrayName1, arrayName2;

Syntax to access an array component: arrayName[indexExp]

intExp = number of components in array >= 0 0 <= indexExp <= intExp

One-Dimensional Arrays

11

Example9-1 The statement:

int[] num = new int[5]; Declares and creates the array num of 5 components. Each component is of type int. The components are accessed as:

num[0], num[1],num[2],num[3],num[4]

Array num

12

int[] num = new int[5];

Array num

Why all the values = 0 ???????????

13

When an array is instantiated. Java automatically initializes its components to their default values. For example, numeric arrays are initialized to 0.

What are string, char array initialized to?

Array num

14

Alternate Ways to Declare an array

int list[]; // here [] is after list not int

But take care, what is the difference here:int alpha[], beta;int[] gamma, delta;

It is recommended that you declare arrays as int[].

15

Array list

int [] list = new int[10];

16

Array list

17

int arraySize;

System.out.print("Enter the size of the array: ");

arraySize = console.nextInt();

System.out.println();

int[] list = new int[arraySize];

Arrays that are created during program execution are called dynamic arrays.

Specifying Array Size During Program Execution

18

double[] sales = {12.25, 32.50, 16.90, 23, 45.68};

The values, called initial values, are placed between braces and separated by commas.

Here,

sales[0]= 12.25, sales[1]= 32.50, sales[2]= 16.90, sales[3]= 23.00, and sales[4]= 45.68.

When declaring and initializing arrays, the size of the array is determined by the number of initial values within the braces.

If an array is declared and initialized simultaneously, we do not use the operator new to instantiate the array object.

Array Initialization During Declaration

19

A public instance variable length is associated with each array that has been instantiated.

The variable length contains the size of the array. The variable length can be directly accessed in a program

using the array name and the dot operator.

This statement creates the array list of six components and initializes the components using the values given.

int[] list = {10, 20, 30, 40, 50, 60};

Here, list.length is 6.

Arrays and the Instance Variable length

20

This statement creates the array numList of 10 components and initializes each component to 0.

int[] numList = new int[10];

The value of numList.length is 10.

These statements store 5, 10, 15, and 20, respectively, in the first four components of numList.

numList[0] = 5;numList[1] = 10;numList[2] = 15;numList[3] = 20;

The value of numList.length is still 10.

You can store the number of filled elements, that is, the actual number of elements, in the array in a variable, SAYnoOfElement. It is a common practice for a program to keep track of the number of filled elements in an array.

Arrays and the Instance Variable length

21

Loops used to step through elements in array and perform operations.

int[] list = new int[100];int i;

//process list[i], the (i + 1)th element of listfor (i = 0; i < list.length; i++)

//inputting data to listfor (i = 0; i < list.length; i++) list[i] = console.nextInt();

//outputting data from listfor (i = 0; i < list.length; i++) System.out.print(list[i] + " ");

Remember to start loop counter from 0 because Array index starts from 0.

Processing One-Dimensional Arrays

22

Arrays Some operations on arrays:

Initialize Input data Output stored data Find largest/smallest/sum/average of elements

Example 9_3

double[] sales = new double[10];int index;double largestSale, sum, average;

23

Code to Initialize Array to Specific Value (10.00)

for (index = 0; index < sales.length; index++) sales[index] = 10.00;

Note: .length NOT .length()It is a variable not a method.

24

Code to Read Data into Array

for (index = 0; index < sales.length; index++) sales[index] = console.nextDouble();

25

Code to Print Array

for (index = 0; index < sales.length; index++) System.out.print(sales[index] + " ");

26

Code to Find Sum and Average of Array

sum = 0;for (index = 0; index < sales.length; index++) sum = sum + sales[index];

if (sales.length != 0) average = sum / sales.length;else average = 0.0;

27

Determining Largest Element in Array

maxIndex = 0;

for (index = 1; index < sales.length; index++) if (sales[maxIndex] < sales[index]) maxIndex = index;

largestSale = sales[maxIndex];

28

Determining Largest Element in Array

29

After for loop executes, maxIndex=7 largestSale=sales[maxIndex]= 98.23.

Exercises: How to find the smallest element in an array???? Rewrite the program that we discussed in the

beginning of this chapter: the RevOrd class.

Determining Largest Element in Array

30

Array Index Out of Bounds

An array is in bounds if:

0 <= index <= arraySize – 1

If index < 0 or index > arraySize:

ArrayIndexOutOfBoundsException exception is thrown. If the program does not handle this exception, the program terminates.

31

Base address:

Base address: is the address (memory location) of the first component in an array.

Base address of list is the address of list[0]. Value of variable list is the base address of the array= the

address of list[0].

When you pass an array as a parameter, the base address of the actual array is passed to the formal parameter.

32

Declaring Arrays as Formal Parameters to Methods

General syntax to declare an array as a formal parameter:

dataType[] arrayName

public static void arraysAsFormalParameter(int[] listA, double[] listB, int num){ //...}

int[] intList = new int[10];double[] doubleNumList = new double[15];int number;

arraysAsFormalParameter(intList, doubleNumList, number);

33

The Assignment Operators and Arrays

int listA={5,10,15,20,25,30,35};

int listB=new int[listA.length];

34

You can use the assignment operator(=) to assign listA to listB. However, the result obtained might not be what you expect.

For example: listA = listB; You expect: element of listA are copied to listB.

That is wrong, listA is a refrence varible, both listA and listB refer to the same array.

The Assignment Operators and Arrays

VIP
هنا معناها يأشرون على نفس الاوبجكت مو أنه سوا كوبي منه !

35

The Assignment Operators and Arrays

36

To copy listA components to listB: for (int index = 0; index < listA.length; index++)

listB[index] = listA[index];

The Assignment Operators and Arrays

37

Relational Operators Arrays

if (listA == listB)...

The expression listA == listB determines if the values of listA and listB are the same, thus determining whether listA and listB refer to the same array.

To determine whether listA and listB contain the same elements, you need to compare them component by component.

You can write a method that returns true if two int arrays

contain the same elements.

38

Relational Operators and Arrays

boolean isEqualArrays(int[] firstArray, int[] secondArray){ if (firstArray.length != secondArray.length) return false; for (int index = 0; index < firstArray.length; index++) if (firstArray[index] != secondArray[index]) return false; return true;}

if (isEqualArrays(listA, listB))...

39

Methods for Array Processing

Example 9_5

public static void fillArray(int[] list, int noOfElements)

{

int index;

for (index = 0; index < noOfElements;

index++)

list[index] = console.nextInt();

}

40

public static void printArray(int[] list, int noOfElements){ int index; for (index = 0; index < noOfElements; index++) System.out.print(list[index] + " ");} public static int sumArray(int[] list, int noOfElements){ int index; int sum = 0; for (index = 0; index < noOfElements; index++) sum = sum + list[index]; return sum;}

Methods for Array Processing

41

public static int indexLargestElement(int[] list, int noOfElements){ int index; int maxIndex = 0; for (index = 1; index < noOfElements; index++) if (list[maxIndex] < list[index]) maxIndex = index; return maxIndex;}

public static void copyArray(int[] list1, int[] list2, int noOfElements){ int index; for (index = 0; index < noOfElements; index++) list2[index] = list1[index];}

Methods for Array Processing

42

You MUST Check example9_6 for calling these methods.

Methods for Array Processing

43

Parallel Arrays Arrays are parallel if the corresponding components hold related information. Example: You need to keep track of 50 students ID with their grades.

Int [] studentId = new int[50];Char[] courseGrade = new char[50];

studentId[3] and courseGrade[3] holds the data for the same student.

studentId courseGrade 2345 A

4563 C4590 C2404 B

44

Arrays of Objects

Can use arrays to manipulate objects. Example: Create an array named array1 with N

objects of type T:

T[] array1 = new T[N] Can instantiate array1 as follows:

for(int j=0; j <array1.length; j++)

array1[j] = new T();

45

Array of String Objects

String[] nameList = new String[5];

nameList[0] = "Amanda Green";

nameList[1] = "Vijay Arora";

nameList[2] = "Sheila Mann";

nameList[3] = "Rohit Sharma";

nameList[4] = "Mandy Johnson";

46

Array of String Objects

47

You can use String methods to work with the objects of nameList.

nameList[0].equals(“Amanda Green”) // true

nameList[4].substring(0,5) //Mandy

Array of String Objects

48

Clock[] arrivalTimeEmp = new Clock[100];

Arrays of Objects of Other Classes

49

Instantiating Array Objectsfor (int j = 0; j < arrivalTimeEmp.length; j++) arrivalTimeEmp[j] = new Clock();

50

arrivalTimeEmp[49].setTime(8, 5, 10);

Instantiating Array Objects

51

Arrays and Variable Length Parameter List

The syntax to declare a variable length formal parameter (list) is:

dataType ... identifier

52

Arrays and Variable Length Parameter List

public static double largest(double ... numList){ double max; int index; if (numList.length != 0) { max = numList[0]; for (index = 1; index < numList.length; index++) { if (max < numList [index]) max = numList [index]; } return max; } return 0.0;}

53

Arrays and Variable Length Parameter List

double[] numberList = {18. 50, 44, 56.23, 17.89

92.34, 112.0, 77, 11, 22,

86.62);

System.out.println(largest(numberList));

54

Rules to follow when using a variable length formal parameter list:

1. A method can have both a variable length formal parameter and other formal parameter.

public static void myMethod (String name, double num, int … intList)

2. A method can have at most one varible length formal parameter.

3. If a method has both a variable length formal parameter and other formal parameter, then the variable length formal parameter must be the last).

Arrays and Variable Length Parameter List

55

foreach loop

The most recent version of Java provides a special type of for loop to process the elements of an objects such as an array.

The syntax to use this for loop to process the elements of an array is:

for (dataType identifier : arrayName)

statements

identifier is a variable, and the data type of identifier is the same as the data type of the array components.

This form of for is called a foreach loop.

56

foreach loop

sum = 0; //line1for (double num : list) //line2 sum = sum + num; //line3

The for statement in Line 2 is read for each num in list. The identifier num is initialized to list[0]. In the next iteration, the value of num is list[1], and so on.

for (double num : numList){ if (max < num) max = num;}

57

[Red] [Brown] [Black] [White] [Gray]

[GM] 10 4 95 3 5

[Ford] 6 3 6 6 4

[Toyota] 3 5 3 6 7

[BMW] 8 2 7 5 3

[Nissan] 0 4 5 33 4

[Volvo] 1 5 7 9 7

Two-Dimensional ArraysinStock

58

Two-Dimensional Arrays Data is sometimes in table form (difficult to represent using a

one-dimensional array).

To declare/instantiate a two-dimensional array:

dataType[ ][ ] arrayName = newdataType[intExp1][intExp2];

To access a component of a two-dimensional array:arrayName[indexExp1][indexExp2];

intExp1, intExp2 >= 0 indexExp1 = row position indexExp2 = column position

59

double[][]sales = new double[10][5];

Two-Dimensional Arrays

60

Accessing Two-Dimensional Array Components

=25.75

61

int [][] matrix = new int[20][15];

20 rows

15 columns

matrix.length = 20 //number of rows Each row of matrix is 1-D array

matrix.[0].length = 15 //# of columns in 1st row

matrix.[1].length = 15 // # of columns in 2nd row

Two-Dimensional Arrays

62

Two-Dimensional Arrays: Special Cases

Can specify different number of columns for each row (ragged arrays). In this case, each row must be instantiated separately.

63

Two-Dimensional Arrays:Special Cases

To create this array, first we create 1-D array board of 5 rows:

int[] board = new int[5];board[0] = new int[6];

board[1] = new int[2];

board[2] = new int[2];

board[3] = new int[3];

board[4] = new int[4];

64

Two Dimensional Array Initialization During Declaration

int[][] board = {{2,3,1} , {15,25,13} , {20, 4, 7}};

[0] [1] [2]

[0] 2 3 1

[1] 15 25 13

[2] 20 4 7

board

What is the array created after this statement: int[][] table = {{2,3,1,5} , {15,25} , {4, 23, 45}};

65

Processing Two Dimensional Array

Three ways to process two-dimensional arrays: Entire array. Particular row of array (row processing). Particular column of array (column processing).

Processing algorithms is similar to processing algorithms of one-dimensional arrays.

The following declarations are used for our examples:static final int ROWS=7;static final int COLUMNS=6;int[][] matrix = new int [ROWS][COLUMNS];int row, col, sum, largest, temp;

66

Loop for processing row 5 elements: for (col=0; col < matrix[5].length; col++) //process matrix[5][col]

Loop for processing column 2 elements: for (row=0; row < matrix.length; row++)

//process matrix[row][2]

Two-Dimensional Arrays: Processing

67

Two-Dimensional Arrays: Processing

Initialization

for (row = 0; row < matrix.length; row++) for (col = 0; col < matrix[row].length; col++) matrix[row][col] = 10;

Print

for (row = 0; row < matrix.length; row++){ for (col = 0; col < matrix[row].length; col++) System.out.printf("%7d", matrix[row][col]); System.out.println();}

68

Input

for (row = 0; row < matrix.length; row++) for (col = 0; col < matrix[row].length; col++) matrix[row][col] = console.nextInt();

Sum by Row

for (row = 0; row < matrix.length; row++){ sum = 0; for (col = 0; col < matrix[row].length; col++) sum = sum + matrix[row][col]; System.out.println("Sum of row " + (row + 1) + " = "+ sum);}

Two-Dimensional Arrays: Processing

69

Sum by Column

for (col = 0; col < matrix[0].length; col++){ sum = 0; for (row = 0; row < matrix.length; row++) sum = sum + matrix[row][col]; System.out.println("Sum of column " + (col + 1) + " = " + sum);}

Two-Dimensional Arrays: Processing

70

Largest Element in Each Row

for (row = 0; row < matrix.length; row++){ largest = matrix[row][0]; for (col = 1; col < matrix[row].length; col++) if (largest < matrix[row][col]) largest = matrix[row][col]; System.out.println("The largest element of row " + (row + 1) + " = " + largest);}

Two-Dimensional Arrays: Processing

71

Largest Element in Each Column

for (col = 0; col < matrix[0].length; col++){ largest = matrix[0][col]; for (row = 1; row < matrix.length; row++) if (largest < matrix[row][col]) largest = matrix[row][col]; System.out.println("The largest element of col " + (col + 1) + " = " + largest);}

Two-Dimensional Arrays: Processing

72

Multidimensional Arrays

Can define three-dimensional arrays or n-dimensional arrays (n can be any number).

Syntax to declare and instantiate array:

dataType[][]…[] arrayName = new dataType[intExp1][intExp2]…[intExpn];

Syntax to access component:

arrayName[indexExp1][indexExp2]…[indexExpn]

intExp1, intExp2, ..., intExpn = positive integers indexExp1,indexExp2, ..., indexExpn = non-negative

integers

73

Loops to Process Multidimensional Arrays

double[][][] carDealers = new double[10][5][7];

for (i = 0; i < 10; i++) for (j = 0; j < 5; j++) for (k = 0; k < 7; k++) carDealers[i][j][k] = 10.00;

Chapter 10: Applications of Arrays

Java Programming:

From Problem Analysis to Program Design,

Second Edition

Java Programming: From Problem Analysis to Program Design, Second Edition 75

Chapter Objectives

Learn how to implement the sequential search algorithm.

Explore how to sort an array using selection sort. Become aware of the class Vector. Become aware of the Wrapper classes.

Java Programming: From Problem Analysis to Program Design, Second Edition 76

List Processing

List: A set of values of the same type. Basic operations performed on a list:

Search list for given item. Sort list. Insert item in list. Delete item from list.

Java Programming: From Problem Analysis to Program Design, Second Edition 77

Search

Necessary components to search a list: Array containing the list. Length of the list. Item for which you are searching.

After search completed: If item found, report “success” and return location

in array. If item not found, report “failure.”

Java Programming: From Problem Analysis to Program Design, Second Edition 78

Searchpublic static int seqSearch(int[] list, int listLength, int searchItem){ int loc; boolean found = false; for (loc = 0; loc < listLength; loc++) if (list[loc] == searchItem) { found = true; break; } if (found) return loc; else return -1;}

Java Programming: From Problem Analysis to Program Design, Second Edition 79

Selection Sort

List is sorted by selecting list element and moving it to its proper position.

Algorithm finds position of smallest element and moves it to top of unsorted portion of list.

Repeats process above until entire list is sorted.

VIP
يبغى يرتب حسب الاصغر !

Java Programming: From Problem Analysis to Program Design, Second Edition 80

Selection Sort

Java Programming: From Problem Analysis to Program Design, Second Edition 81

Selection Sort

Java Programming: From Problem Analysis to Program Design, Second Edition 82

public static void selectionSort(int[] list, int listLength){ int index; int smallestIndex; int minIndex; int temp; for (index = 0; index < listLength – 1; index++) { smallestIndex = index; for (minIndex = index + 1; minIndex < listLength; minIndex++) if (list[minIndex] < list[smallestIndex]) smallestIndex = minIndex;

temp = list[smallestIndex]; list[smallestIndex] = list[index]; list[index] = temp; }}

Selection Sort

Java Programming: From Problem Analysis to Program Design, Second Edition 83

For a list of length n, an average selection sort makes n(n – 1) / 2 key comparisons and 3(n – 1) item assignments.

Therefore, if n = 1000, selection sort makes about 500,000 key comparisons and about 3000 item assignments to sort the list.

Selection Sort

Java Programming: From Problem Analysis to Program Design, Second Edition 84

Vectors

The class Vector can be used to implement a list.

Unlike an array, the size of a Vector object can grow/shrink during program execution.

You do not need to worry about the number of data elements in a vector.

Java Programming: From Problem Analysis to Program Design, Second Edition 85

Members of the class Vector

Java Programming: From Problem Analysis to Program Design, Second Edition 86

Members of the class Vector

Java Programming: From Problem Analysis to Program Design, Second Edition 87

Members of the class Vector

Java Programming: From Problem Analysis to Program Design, Second Edition 88

Members of the class Vector

Java Programming: From Problem Analysis to Program Design, Second Edition 89

Vectors

Every element of a Vector object is a reference variable of the type Object.

To add an element into a Vector object: Create appropriate object. Store data into object. Store address of object holding data into Vector object element.

Java Programming: From Problem Analysis to Program Design, Second Edition 90

Vector<String> stringList = new Vector<String>();

stringList.addElement("Spring");stringList.addElement("Summer");stringList.addElement("Fall");stringList.addElement("Winter");

Vectors

Java Programming: From Problem Analysis to Program Design, Second Edition 91

Wrapper Classes

Algorithms are used to implement operations. Construct and implement your own methods. Classes Integer, Double, Character, Long, Float: Known as wrapper classes. Provided so that values of primitive data types can

be treated as objects. Have limitations (cannot change value stored in

objects).

Java Programming: From Problem Analysis to Program Design, Second Edition 92

The class Integer

Java Programming: From Problem Analysis to Program Design, Second Edition 93

The class Integer

Java Programming: From Problem Analysis to Program Design, Second Edition 94

The class Integer

Integer num; num = new Integer(86)

Java Programming: From Problem Analysis to Program Design, Second Edition 95

The class Integerint x; Integer num;

num = 25;

This statement is equivalent to the statement:

num = new Integer(25);

The expression: num = 25;

is referred to as autoboxing of the int type.

Java Programming: From Problem Analysis to Program Design, Second Edition 96

The class Integer

int x;

Integer num;

The statement:

x = num;

This statement is equivalent to the statement:

x = num.intValue();

This statement is referred to as auto unboxing of the int type.

Java Programming: From Problem Analysis to Program Design, Second Edition 97

The class Integer

To compare the values of two Integer objects, you can use the method compareTo.

If you want to compare the values of two Integer objects only for equality, then you can use the method equal.

Java Programming: From Problem Analysis to Program Design, Second Edition 98

The class IntClass

Java Programming: From Problem Analysis to Program Design, Second Edition 99

The class IntClass

Recommended