chapter 5: arrays arrays. why do we need arrays? java programming: from problem analysis to program...

Post on 13-Jan-2016

252 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Chapter 5: ARRAYS

ARRAYS

Why Do We Need Arrays?

Java Programming: From Problem Analysis to Program Design, 4e

2

We want to write a Java program that reads five numbers, finds their sum, and prints the numbers in reverse order.

System.out.println("Enter five integers: "); item0 = console.nextInt();item1 = console.nextInt();item2 = console.nextInt(); item3 = console.nextInt(); item4 = console.nextInt(); sum = item0 + item1 + item2 + item3 + item4; System.out.println("The sum of the numbers = " + sum); System.out.print("The numbers in reverse order are: "); System.out.println(item4 + " " + item3 + " " + item2 + " " + item1 + " " + item0);

Why Do We Need Arrays?

Java Programming: From Problem Analysis to Program Design, 4e

3

item0

item1

item2

item3

item4

Note the following in the preceding program:

1. Five variables must be declared because the

numbers are to be printed in reverse order.

2. All variables are of type int—that is, of the same

data type.

3. The way in which these variables are declared

indicates that the variables to store these numbers have

the same name except for the last character, which is a

number.

item[0]

item[1]

item[2]

item[3]

item[4]

in Java is called an

array.

Chapter Objectives

Java Programming: From Problem Analysis to Program Design, 4e

4

Learn about arrays Explore how to declare and manipulate data

into arrays Understand the meaning of “array index out of

bounds” Become familiar with array processing and its

restrictions

Array

Java Programming: From Problem Analysis to Program Design, 4e

5

Definition: structured data type with a fixed number of elements

Elements of an array are also called components of the array

Every element is of the same type Elements are accessed using their relative

positions in the array

One-Dimensional Arrays

Java Programming: From Problem Analysis to Program Design, 4e

6

One-Dimensional Arrays (continued)

Java Programming: From Problem Analysis to Program Design, 4e

7

• Array num:int[] num = new int[5];

8

Java Programming: From Problem Analysis to Program Design, 4e

Arrays

When an array is instantiated, Java automatically initializes its

elements to their default values.

numeric arrays are initialized to

0,

char arrays are initialized to the

null character, which is '\u0000',

boolean arrays are initialized to

false.

• Array num:int[] num = new int[5];

Java Programming: From Problem Analysis to Program Design, 4e

9

Arrays (continued)

To save space, we also draw an array, as shown in Figures 9-2(a) and 9-2(b).

One-Dimensional Arrays (continued)

Java Programming: From Problem Analysis to Program Design, 4e

10

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

Array List

Java Programming: From Problem Analysis to Program Design, 4e

11

Array List (continued)

Java Programming: From Problem Analysis to Program Design, 4e

12

Array List (continued)

Java Programming: From Problem Analysis to Program Design, 4e

13

Array List (continued)14

Java Programming: From Problem Analysis to Program Design, 4e

Java Programming: From Problem Analysis to Program Design, 4e

15

Specifying Array Size During Program Execution

Java Programming: From Problem Analysis to Program Design, 4e

16

The initializer list contains values, called initial values, that are placed between braces and separated by commas

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

Array Initialization During Declaration

Array Initialization During Declaration (continued)

Java Programming: From Problem Analysis to Program Design, 4e

17

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

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 don’t use the operator new to instantiate the array object

Arrays and the Instance Variable length

Java Programming: From Problem Analysis to Program Design, 4e

18

Associated with each array that has been instantiated, there is a public (final) instance variable length

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

Arrays and the Instance Variable length (continued)

Java Programming: From Problem Analysis to Program Design, 4e

19

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

This statement creates the array list of six components and initializes the components using the values given Here list.length is 6

int[] numList = new int[10];

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

Arrays and the Instance Variable length (continued)

Java Programming: From Problem Analysis to Program Design, 4e

20

The value of numList.length is 10 numList[0] = 5;numList[1] = 10;numList[2] = 15;numList[3] = 20;

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

You can store the number of filled elements, that is, the actual number of elements, in the array in a variable, say numOfElement

It is a common practice for a program to keep track of the number of filled elements in an array

Array Index Out of Bounds Exception

double[] num = double[10];

int i; The element num[i] is valid, that is, i is a valid

index if i = 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9. The index—say, index—of an array is in

bounds if index >= 0 and index <= arraySize - 1.

If either index < 0 or index > arraySize - 1, then we say that the index is out of bounds.

Java Programming: From Problem Analysis to Program Design, 4e

21

Reading Assignment

What is the difference between the following declaration

int alpha[], beta;

int[ ] gamma, delta;

Java Programming: From Problem Analysis to Program Design, 4e

22

Processing One-Dimensional Arrays

23

Java Programming: From Problem Analysis to Program Design, 4e

Processing One-Dimensional Arrays

Java Programming: From Problem Analysis to Program Design, 4e

24

Loops used to step through elements in array and perform operations

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

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

for (i = 0; i < list.length; i++) list[i] = console.nextInt();

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

Arrays (continued)

Java Programming: From Problem Analysis to Program Design, 4e

25

Some operations on arrays Initialize Input data Output stored data Find largest/smallest/sum/average of elements Search for an element

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

Code to Initialize Array to Specific Value (10.00)

Java Programming: From Problem Analysis to Program Design, 4e

26

//Code to Initialize Array to Specific Value //(10.00)

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

Code to Read Data into Array

Java Programming: From Problem Analysis to Program Design, 4e

27

//Code to Read Data into Array

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

Code to Print Array

Java Programming: From Problem Analysis to Program Design, 4e

28

//Code to Print Arrayfor (int index = 0; index < sales.length;index++) System.out.print(sales[index] + " ");

What will happen if we print array name

System.out.print(sales + " ");

Java Programming: From Problem Analysis to Program Design, 4e

29

Code to Find Sum and Average of Array

Java Programming: From Problem Analysis to Program Design, 4e

30

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

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

Determining Largest Element in Array

Java Programming: From Problem Analysis to Program Design, 4e

31

maxIndex = 0;

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

largestSale = sales[maxIndex];

Determining Largest Element in Array (continued)

32

Java Programming: From Problem Analysis to Program Design, 4e

Determining Largest Element in Array (continued)

Java Programming: From Problem Analysis to Program Design, 4e

33

34

Searching for specific

Search for 10 Search starts at the first element in the list, that is, at list[0]

This time, the search item, which is 10, is compared with every item in the list; eventually, no more data is left in the list to compare with the search item; this is an unsuccessful search

Java Programming: From Problem Analysis to Program Design, 4e 34

35

searchItem = 10; //can be parameter to a method int listLength = sales.length; int loc; boolean found = false; loc = 0; while (loc < listLength && !found) if (sales[loc] == searchItem) found = true; else loc++;

if (found)

System.out.print(loc); else

System.out.print(“not found”);

Java Programming: From Problem Analysis to Program Design, 4e 35

Array Index Out of Bounds

Java Programming: From Problem Analysis to Program Design, 4e

36

Array in bounds if:0 <= index <= arraySize – 1

If index < 0 or index > arraySize:

ArrayIndexOutOfBoundsException exception is thrown

Base address: memory location of first component in array

The Assignment Operators and Arrays

Java Programming: From Problem Analysis to Program Design, 4e

37

The Assignment Operators and Arrays (continued)

Java Programming: From Problem Analysis to Program Design, 4e

38

The Assignment Operators and Arrays (continued)

Java Programming: From Problem Analysis to Program Design, 4e

39

Relational Operators and Arrays

Java Programming: From Problem Analysis to Program Design, 4e

40

• if (listA == listB)...- The expression listA == listB determines if the values of listA and listB are the same and thus determines 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

Relational Operators and Arrays (continued)

Java Programming: From Problem Analysis to Program Design, 4e

41

int[] firstArray; int[] secondArray;

if (firstArray.length != secondArray.length) ………;

for (int index = 0; index < firstArray.length; index++) if (firstArray[index] != secondArray[index]) ……; ……;

Relational Operators and Arrays (example)

Java Programming: From Problem Analysis to Program Design, 4e

42

boolean areEqualArray= true;if(ListA.length != ListB.length){ areEqualArray=false;}elsefor (int index = 0; index < ListA.length;index++) if (ListA[index] != ListB[index]) { areEqualArray=false; break; } if (areEqualArray) System.out.println("they are equals");else System.out.println("they are not equals");

top related