chapter 8 arrays

46
©2004 Brooks/Cole CHAPTER 8 ARRAYS Click the mouse to move to the next page. Use the ESC key to exit this chapter. This chapter in the book includes: 8.1 One-Dimensional Arrays 8.2 Array Initialization 8.3 Arrays and Arguments 8.4 Two-Dimensional Arrays 8.5 Common Programming Errors 8.6 Chapter Summary

Upload: dennis

Post on 13-Jan-2016

85 views

Category:

Documents


2 download

DESCRIPTION

CHAPTER 8 ARRAYS. This chapter in the book includes: 8.1One-Dimensional Arrays 8.2Array Initialization 8.3Arrays and Arguments 8.4Two-Dimensional Arrays 8.5Common Programming Errors 8.6Chapter Summary. Click the mouse to move to the next page. Use the ESC key to exit this chapter. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

CHAPTER 8ARRAYS

Click the mouse to move to the next page.Use the ESC key to exit this chapter.

This chapter in the book includes:8.1 One-Dimensional Arrays8.2 Array Initialization8.3 Arrays and Arguments8.4 Two-Dimensional Arrays8.5 Common Programming Errors8.6 Chapter Summary

Page 2: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Arrays

Primitive scalar variables can contain a single value, like a one family house

Array Variables

are more like an Apartment and may contain several elements with the same address, or location

3

2

1

0

X Y

Page 3: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

One Dimensional ARRAYS

• A simple list containing individual items of the same type is called a one dimensional array, or vector, or list.

• When the new operator is used to create storage for an array, the individual elements are automatically initialized:– To zero for numerical types– To false for boolean types and– To null for reference types

Page 4: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Figure 8.1: Three Lists of Items

Page 5: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Figure 8.2: A List of Prices

Page 6: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Figure 8.3: The Results of the Declaration double prices[];

(Declaring an Array Creates a Reference Variable)

Page 7: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Figure 8.4: The Results of the Allocationprices = new double[6];

Page 8: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Array Elements

• All elements in an array must be the same data type, that is all ints or all char, etc.

• Each item in the array is referred to as an element or component of the array.

• Array elements can be accessed all at once using a for loop or individually using the element’s index, subscript or position number.

• ( Example grade [4] or prices [2] )• The index of the beginning of an array is

always zero.

Page 9: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Figure 8.5: The Arrays Referenced bygrade and code

Page 10: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Figure 8.6: Identifying Individual Array Elements

Page 11: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Figure 8.7: Accessing an Individual Array Element: Element 3

Page 12: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Figure 8.8a: The Declaration String names[];

Creates a Single Reference Variable

Page 13: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Figure 8.8b: The Allocation names = new String[4] Creates an Array of References

Page 14: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Figure 8.8c: The Assignment of Values Creates Actual Array Objects

Page 15: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Figure 8.9: A Programming View of thenames Array

Page 16: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

public class StringArray

{

public static void main(String[] args)

{

int i;

String names[ ]; // declare the array

names = new String[4]; // allocate the array

// assign values to each array element

names[0] = "Joe";

names[1] = "Harriet";

names[2] = "Allyn";

names[3] = "Roberta";

// display the names

for (i = 0; i < names.length; i++)

System.out.println("names[" + i + "] is " + names[i]);

}

}

Page 17: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Run Time Dimensioning

• The size of the array can be entered interactively by the user at run time.s1 = JOptionPane.showInputDialog( “How many grades?”);

numgrades = Integer.parseInt( s1);

int grade [ ] = new int[numgrades];

• The size of the array depends on the value entered by the user

Page 18: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Array Initialization

• Array elements can be initialized by:– Including the elements in curly braces and NOT

specifiying the size of the arrayint grade[] = {98,87,92,79,95};

– Interactively using a for loop for ( i=0; i < grade.length; i++) grade [i] = 0;– An array of characters cannot be initialized with a

stringchar code [ ] = { ‘h’,’e’,’l’,’l’,’o’} //okchar code [ ] = “hello” // invalid

Page 19: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

public class InitializeNames

{

public static void main(String[] args)

{

int i;

String names[] = {"Joe", "Harriet", "Allyn", Roberta"};

// display the names

for (i = 0; i < names.length; i++)

System.out.println("names[" + i + "] is " + names[i]);

}

}

Page 20: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Searching

• Searching a list sequentially means looking at each individual element in the list-– You may want to count certain elements (for

example: votes, positive numbers, honor grades, failures, etc.)

– You may just want to know if an item was in the list (for example: student in a class, sale item ,etc.)

– You may want the largest or smallest value.

Page 21: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

public class FindMaxValue

{

public static void main(String[] args)

{

int i, max;

int nums[] = {2, 18, 1, 27, 16};

max = nums[0]; // start with first value

for (i = 1; i < nums.length; i++)

if ( max < nums[i])

max = nums[i]; // store or “remember” largest

System.out.println("The maximum value is " + max);

}

}

Page 22: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Copying an Array

• Elements from one array can be copied into another array.

• System.arraycopy is a method that copies each element, one by one, from one array into a second array. The result is two distinct arrays.

• System.arraycopy requires 5 arguments

• System.arraycopy(source, startindex, target, start index, number of elements to copy)– System.arraycopy (first,1,second,1, 3);

Page 23: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Figure 8.10: Initial Allocation for the Arrays Declared in Program 8.7

Page 24: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Figure 8.11: After the Call to System.arraycopy()(DEEP copy)

Page 25: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Deep and Shallow Copies

• Deep copy- copies a specified number (including the entire array) of elements from one array to another- it is an element by element copy– System.arraycopy( nums, 1, newnums, 2, 3);– Copies 3 elements from nums to newnums, beginning

at element 1 an placing it in location 2 in new nums.

• Shallow copy- occurs when an array assignment is executed: newnums = nums;– It copies the address stored in nums to newnums

Page 26: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

public class DeepCopy //Program 8.7

{

public static void main(String[ ] args)

{ int i, max;

int nums[ ] = {2, 18, 1, 27, 16};

int newnums[ ] = new int[nums.length];

// copy all elements from nums to newnums

System.arraycopy(nums, 0, newnums, 0, nums.length);

// display newnums

for (i = 0; i < newnums.length; i++)

System.out.println( "newnums[" + i + "] is " + newnums[i]);

newnums[2] = 50; // this only affects newnums

System.out.println();

// display nums

for (i = 0; i < nums.length; i++)

System.out.println("nums[" + i + "] is " + nums[i]);

}

}

Page 27: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Shallow copies

• Just using an assignment statement toassign the values of one array to an array with a different name produces surprising results.

• If list1 and list2 have been declared as arrays, we would expect that

list2 = list1; would produce a second copy of the list.Does it?

No… instead it just assigns the address of list1 to list2 and both variables now reference the SAME list.

Page 28: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Figure 8.12: The Result of the Shallow Copy Provided by Program 8.8

Page 29: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

public class ShallowCopy

{

public static void main(String[] args)

{

int i;

int nums[ ] = {2, 18, 1, 27, 16};

int newnums[ ] = new int[nums.length];

// this produces a shallow copy

newnums = nums; // this only copies the address

// display newnums

for (i = 0; i < newnums.length; i++)

System.out.println("newnums[" + i + "] is " + newnums[i]);

newnums[2] = 50; // affects both newnums and nums, because they are the same array

System.out.println();

// display nums and note the change

for (i = 0; i < nums.length; i++)

System.out.println("nums[" + i + "] is " + nums[i]);

}

}

Page 30: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Arrays as Arguments

• Individual array elements are passed to methods in the same way as scalar variables.

• Individual elements are passed by value- the method receives a copy of the element, but cannot change it.

• Passing an entire array is easier- it is passed by reference- the method gets access to the actual array, it receives the address or location of the array

Page 31: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Figure 8.14: The Location of the Array is Passed

Page 32: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Arrays as Arguments

• Suppose you have this declaration:

int nums[ ] = new int[5]; // list of 5 integers

• …and this method header

int findMax(int val[ ])

• Then you could pass this array to the method by

findMax(nums) // notice- no [ ]

Page 33: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Figure 8.13: Only One Array is Created

Page 34: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

public class Array Argument

{

public static void main(String[] args)

{ int nums[ ] = {2, 18, 1, 27, 16}; // declare and initialize the array

// call the method

System.out.print("The maximum value is” + findMax(nums));

} // end main

// This is the called method

// It is used to find the maximum value stored in the array

public static int findMax (int vals[ ])

{

int I, max = val[0];

for (i = 0; i < vals.length; i++)

if ( vals[i] < max )

max = vals[i];

return max;

} // end findmax

} // end class

Page 35: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Computing with Arrays

• You can perform logical comparisons and arithmetic computation on individual array elements, for example:

if grade[3] > grade [4]System.out.println( student[3] + “has the higher grade”);

• You can also perform operations on the entire array at once, using a for loop:

for( i=0; i < grade.length; i++)

grade[i] = grade[i] +5;

Page 36: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

public class MultiplyElements

{

public static void main(String[] args)

{ int i;

int nums[ ] = {2, 18, 1, 27, 16};

changeValues(nums); // call the method

// display the values

System.out.print("The values in the nums array are");

for (i = 0; i < nums.length; i++)

System.out.print(" " + nums[i]);

} // multiply each element by 10

public static void changeValues(int vals[])

{ int i;

for (i = 0; i < vals.length; i++)

vals[i] = 10*vals[i];

}

}

Page 37: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Two Dimensional Arrays

• A two dimensional array, is called a table.

• It consists of rows and columns.

• To reserve storage for this array both the number of rows and the number of columns must be included in the declaration:

int val[ ][ ] = new int[3] [4]; //3 rows, 4 columns

or int val [ ] [ ] = { {8, 16, 9, 52},

{3, 15, 27, 6},

{7, 25, 2, 10}};

Page 38: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Figure 8.15: Each Array Element Is Identified by Its Row and Column Position

Page 39: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

public class TableDisplay

{

public static void main(String[ ] args)

{ int i, j;

int val[ ][ ] = {{8,16,9,52}, {3,15,27,6}, {7,25,2,10}};

System.out.print(“ \\nDisplay of val array by explicit element"

+'\n' + val[0][0] + " " + val[0][1] + " "

+ val[0][2] + " " + val[0][3]

+'\n' + val[1][0] + " " + val[1][1] + " "

+ val[1][2] + " " + val[1][3]

+'\n' + val[2][0] + " " + val[2][1] + " "

+ val[2][2] + " " + val[2][3]);

System.out.print("\n\nDisplay of val array using a nested for loop");

for (i = 0; i < val.length; i++)

{ System.out.print(‘ \ n‘ ); // print() a new line for each row

for (j = 0; j < val[i].length; j++)

System.out.print(val[i][j] + " ");

}

System.out.println( );

}

Page 40: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

public class MultipyByTen // This program multiplies each element in a 2-D table by 10

{

public static void main(String[] args)

{

int i, j;

int val[ ][ ] = {{8,16,9,52}, {3,15,27,6}, {7,25,2,10}};

// multiply each element by 10 and display it

System.out.print("\n Display of multiplied elements");

for (i = 0; i < val.length; i++)

{

System.out.println( ); // start each row on a new line

for (j = 0; j < val[i].length; j++)

{

val[i][j] = val[i][j] * 10; // multiply by 10

System.out.print(val[i][j] + " ");

} // end of inner loop

} // end of outer loop

System.out.println();

}

}

Page 41: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Passing 2 Dimensional Arrays

• Passing 2-D arrays is identical to passing a single- dimensional array.

• Because a reference is passed, the method receives access to the entire array, so any changes made to the array in the method is made directly to the array.

Page 42: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Public class PassTwodimensional

{ public static void main(String[] args)

{ int val[ ][ ] = {{8,16,9,52},

{3,15,27,6},

{7,25,2,10}};

display (val); // call just passes the indetifier

} // end main

public static void display(int nums[ ][ ]) //header shows 2 dimensions

{

int i, j;

for (i = 0; i < nums.length; i++)

{

for(j = 0; j < nums[i].length; j++)

System.out.print(nums[i][j] + " ");

System.out.println();

} // end for

} // end display method

} // end class

Page 43: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Advanced Dimensions

• Java has the ability to create arrays in which each row has a different number of columns.

• Java also allows larger arrays with any number of dimensions.

• Rules for these larger dimensional arrays are the same as for single dimensions. ( See pp.326-79)

Page 44: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Figure 8.16: Representation of aThree-Dimensional Array

Page 45: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Common Programming Errors

• Forgetting [ ] when declaring an array or in a method header

• Using [ ] in a method call

• Using a subscript value that references a non-existent array element (for example, declaring an array x of size 20 and using x[25]

• Using the wrong counter variables in the loop- or forgetting that arrays always begin with 0

Page 46: CHAPTER 8 ARRAYS

©2004 Brooks/Cole

Some Practice

• Suppose you have 3 arrays declared as:int list[ ] = new int[5];char tictactoe[ ] = new char [3][3];Write headers and calls for methods:Sort the listPlace character on the board to play game Header call

public static void sort (int list[ ] ) sort( list);

public static void play (char tictactoe[ ] [ ]) play(tictactoe);