java programming: from the ground up chapter 7 arrays and lists: one name for many data

77
Java Programming: From the Ground Up Chapter 7 Arrays and Lists: One Name for Many Data

Upload: lesley-norton

Post on 21-Jan-2016

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Java Programming:From the Ground Up

Chapter 7Arrays and Lists:

One Name for Many Data

Page 2: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Arrays

• An array is a named sequence of contiguous memory locations capable of holding a collection of data of the same type.

• Unlike the variables of previous programs, an array can store more than one value.

• An array can store a list of thousands or even millions of data

Page 3: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

A variable in contrast to an array

Page 4: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Array Declaration

• type[] name:

type is a data type such a int, char, double or boolean name is a valid Java identifier that provides a name to

an array

• int[] myArray and double[] yourArray:

The variables myArray and yourArray are reference variables.

A reference variable does not hold an integer, a floating point number, a character or a boolean value.

A reference variable holds a memory address.

Page 5: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Array Declaration

• Java provides two types of variable primitive and reference:

A primitive variable stores a single value of type byte, short, int, long, float, double, boolean, or char.

A reference variable holds a memory address or reference.

  • Each of the two variables myArray and yourArray, when

assigned a value, holds a memory address, the address of the first cell of a block of storage locations

Page 6: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Array Instantiation

• The references myArray and yourArray are uninitialized.

• A declaration does not create an array.

• Once an array reference is declared, memory for the array must be allocated.

Page 7: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Array Instantiation

• An array is created or instantiated via the new operator:

type [] name; // declaration name = new type[size]; // array instantiation or type[] name = new type[size] // declaration and

instantiation

• type is a data type and size is a positive integer or any expression that evaluates, or is automatically converted, to a positive integer.

• The integer size indicates the length of the array, i.e., the

number of cells in the array.

Page 8: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Array Instantiation

• The values held in an array must all be the same data type.

• When an array is created, each cell is automatically given a unique name .

• The names of the cells of the array referenced by myArray are myArray[0], myArray[1], myArray[2], myArray[3], and myArray[4]. In this case, the array is indexed from 0 to 4.

• The first index of every array is 0.

Page 9: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Array Instantiation

• When an array is instantiated, each memory cell is initialized with the “zero value” of its data type.

• Thus every cell of an array of int or char data is initialized to 0 and all cells of an array of doubles are set to 0.0.

• Each cell of a boolean array is initialized to false.

Page 10: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Array Instantiation

int [] numberList;numberList = new int [5]; **********numberList refers to an array of 5 integersEach array cell is initialized to 0

Page 11: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Array Instantiation

System.out.println("Enter array size: ");int size = input.nextInt();double [] decimals;decimals = new double[size]; **********The length of the array (size) is supplied at runtime.

The name decimals refers to an array of doubles.Each memory cell is initialized to 0.0.

Page 12: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Array Instantiation

int x = 3;char [] letters = new char[2*x]; **********letters refers to an array of char data.Each memory cell is initialized to 0.

Page 13: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Array Instantiation

• Once an array is created, its length is fixed.

• The length of an array cannot be altered.

• If variable x refers to an array, then x.length gives the number of memory cells allocated to the array.

Page 14: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Using an Array

• You can use array variables in assignment statements or any expression.

 The statement:

int[] numbers = new int[5]

declares and instantiates an array named numbers such that:

• numbers is indexed from 0 to 4.

• numbers is capable of storing 5 integers in locations numbers[0], numbers[1], numbers[2], numbers[3], and numbers[4].

• numbers.length has the value 5.

• the initial value stored in each cell of numbers is 0.

Page 15: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Using an Array

Each memory cell is a variable:

• numbers[0] = input.nextInt(); // reads a value into numbers[0]

• numbers[1] = 213 + numbers[1]; // adds 213 to numbers[1]

• System.out.println(5*numbers[1] + 3*numbers[0]);

Page 16: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Using an Array

Program statement: • Write a program that prompts for 10 integers and displays those same numbers

in reverse order. For example, if you enter the numbers:

0 11 2 33 4 55 6 77 8 99

the program’s output is:

99 8 77 6 55 4 33 2 11 0

Page 17: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Solution

:

• The following application stores 10 integers in an array named list.

• The array consists of 10 memory cells that are named list[0], list[1]...list[9]. The user supplies 10 numbers.

• The numbers are stored in these 10 cells and finally, the numbers are displayed in reverse order.

 

Page 18: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

1. import java.util.*;2. public class ReverseList3. {4. public static void main(String[] args)5. {6. Scanner input = new Scanner(System.in);7. int [] list; // declare list an array variable8. list = new int[10]; //instantiate or create an array named list9. System.out.print("Enter 10 integers: ");10. // read values into list[0], list[1],..,list[9]11. for (int i= 0; i < 10; i++)12. list[i] = input.nextInt(); 13. System.out.print("List in reverse : ");14. //print values stored in list[9], list[8], … , list[0]15. for (int i= 9; i >= 0; i--)16. System.out.print(list[i] + " ");17. System.out.println();18. }19. }

 

Page 19: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Discussion

The program prompts for 10 integers. After the data is entered (lines 11-12):

The array list holds 10 integers.

The individual memory cells are designated list[0], list[1], list[2], ... , list[8], and list[9]

Page 20: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Discussion

Line 7: int [] list;

• Line 7 is an array declaration as indicated by the square brackets [].

• Like any variable, list must be declared before its use.

• The statement on line 7 declares that list is a reference variable

• The declaration does not assign a value to list.

• No memory has been allocated yet; no array exists yet. 

Page 21: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Discussion

Line 8: list = new int[10];

• The segment new int[10] allocates a block of memory large enough to store ten integers, and returns the starting address of this memory chunk.

• The new operator creates or instantiates a new array.

• The operator reserves a consecutive block of storage locations in memory, and returns the starting address of the block. All are initialized to 0:

Page 22: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

list

Page 23: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Discussion

Lines 11 and 12: for (int i= 0; i < 10; i++) list[i] = input.nextInt(); • Lines 11 and 12 comprise a for loop that accepts interactive input

and stores the values in list[0], list[1], list[2], list[3], list[4], list[5], list[6], list[7], list[8], and list[9].

Page 24: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Discussion

Lines 15 and 16: for (int i= 9; i >= 0; i--) System.out.print(list[i] + " ");

The for loop prints the array items in reverse.: list[9], list[8], …, and list[0].

Page 25: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Array Initialization

• Java provides a convenient form of array initialization.

• The following code segment declares and explicitly initializes an array of characters:

char letters[] = {'a', 'b', 'c'}; • The new operator is not explicitly used.

• This initialization of letters is equivalent to:

char letters[] ;letters = new char[3];letters[0] = 'a';letters[1] = 'b';letters[2] = 'c';

 • .

Page 26: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Array Initialization

• Similarly:

int squares = {0,1,4,9,16,25,36,49,64,81,100};

is shorthand for:

int squares = new int[10];for (int i= 0; i<11; i++ )squares[i] = i*i;

 • Explicit method of array initialization is convenient only when

the size of the array is not particularly large

Page 27: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

The = Operator

• The assignment operator (=) can be used with array references, but such use can lead to some unexpected results and subtle bugs:

int [] a = {5,4,3,2,1};int [] b = new int[5]; // initialized to 0’sb = a;a[0] = 100;System.out.println(“ a[0] is ” + a[0]+ “ and b[0] is ” +b[0]);

 • Output:

a[0] is 100 and b[0] is 100

• Both a[0] and b[0] are 100.

• a and b are both references, i.e., a and b each holds a single address.

Page 28: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

The = Operator

int a = {5,4,3,2,1}Int b = new int[5]

Page 29: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

The = Operator

b = a

After the assignment b=a

Page 30: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

The = Operator

B[0] = 100;

After executing the assignment b=a, the references a and b both refer to the same memory and any changes to a[i] affect b[i].

Page 31: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

The == Operator

• The == operator does not compare the contents of the arrays; the == operator compares references.

 • int[] a = {5,4,3,2,1};• int[] b = {5,4,3,2,1}; • int[] c = a;

• The expression a == b is false because a and b hold different references

• a == c evaluates to true.

Figure 7.13 Comparing array references

Page 32: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Arrays and Methods

• An array reference can be passed as a parameter to a method.

• When an array is passed to a method, only the reference or address of the array is copied to the parameter of the method.

• The values stored in the array are not passed or copied.

Page 33: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Arrays and Methods

If an array reference x is passed as an argument to a parameter data then both x and data refer to the same memory block:

public static void changeMe(int[] data){ data[0] = 200; data[1] = 400;}public static void main(String [] arga){ int x[] = {2, 4, 6, 8}; changeMe(x); System.out.print(“x now has values ”+ x[0]+ “ ”+x[1]+ “ ”+ x[2]+ “ ” + x[3]); }

Page 34: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Arrays and Methods

When x is passed as an argument to:

changeMe( int[] data)

the address that is stored in x is passed to data.

• data and x refer to the same block of memory;

• changeMe(...) assigns new values (200 and 400) to data[0] and data[1] and consequently to x[0] and x[1]

• When the changeMe(...) returns, the final print(..) statement displays:

x now has values 200 400 6 8

Both argument x and parameter data refer to the same array.

Page 35: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Arrays and Methods

Write a method:  void swap(int [] x, int i, int j)

that accepts three parameters:

• an array reference x• two array indices i and j

 and interchanges the contents of x[i] and x[j]:

public static void swap ( int[] x, int i, int j) { // swaps x[i] and x[j] int temp = x[i]; x[i] = x[j]; x[j] = temp; } In main:

int [] a = { 1,3,5,7,9};swap(a, 2,4) // swap a[2] and a[4]

 Before: 1 3 5 7 9After: 1 3 9 7 5

Page 36: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Insertion Sort

An array of integers, partially sorted:

[2 3 5 9 4]

• The last element must be inserted into the sorted group at its correct position. To place this number (4) into its proper position:

• Copy the value in the last position (4) to a temporary variable, temp, so that the value is “safe.” That is, the value is put aside for safe keeping.

• Compare 4 to 9, the element in the last position of the sorted sub-array. Since 9 is larger, 4 precedes 9 in the sorted array; so shift (copy) 9 one position to the right :

[2 3 5 9 4] [2 3 5 9 9]. We did not “lose” the 4; it is stored in temp.

• Compare 4 to 5. Since 5 is the larger number, shift 5 one position to the right:

[2 3 5 9 9] [2 3 5 5 9]

• Compare 4 to 3. Since 3 is less than 4, the correct position of 4 has been found. Now, place 4, which has been saved in temp, in the position immediately following 3 and stop. The value 4 now sits in its correct place following 3 and preceding 5:

[2 3 5 5 9] [2 3 4 5 9]

Page 37: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Insertion Sort

Insert a number into its correct position within a sorted list

Page 38: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Insertion Sort

This insertion process can be implemented as a void method

void insert(int[] x, int i)

that places the ith value of x into its proper position among the sorted values x[0], x[1],…x[i-1], shifting numbers to the right if necessary.

The method operates as follows:

• copy x[i] into a temporary variable, temp.• initialize a counter j to i-1, the largest index of the sorted sub-array.• while (j >= 0 and temp < x[j] )• copy x[j] to x[j+1] and decrement j // shift.• copy temp to x[j+1].

Page 39: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Putting the Insertion Method to Work

• To sort an array of n elements, insertion sort invokes the insert(...) method n – 1 times

• It incrementally builds sorted sub-arrays (x[0] x[1]), then (x[0] x[1] x[2]), then

(x[0] x[1] x[2] x[3])…and finally (x[0] x[1] x[2] x[3]…x[n-1]).

Insertion sort calls insert n-1 times

Page 40: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Problem

Problem statement Implement insertion sort.

Page 41: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Solution

 

1. public static void insert ( int[] x, int i)2. {3. // place x[i] in its proper place among sorted values x[0],

x[1]…x[i-1]4. int temp = x[i]; // save the value5. int j = i-1; 6. while ( j >= 0 && temp <x[j]) //determine where to place temp7. {8. x[j+1] = x[j]; // shift right9. j--;10. }11. x[j+1]= temp; //place temp (x[i]) in its correct position12. }13. public static void insertionsort(int[] x, int n)14. { // n is the number of data stored in array x15. for (int i = 1; i < n; i++)16. insert(x,i); 17. }   • .

Page 42: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Discussion

• The array can be partially filled. The number of elements that must be sorted is size, and not x.length.

• For a data set of size n, insertion sort performs at most ½(n2 – n) comparisons.

• On the other hand, if the data are already sorted, insertion sort makes just n – 1 comparisons

Page 43: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Linear Search

Begin with x[0] and successively compare key to each item in the array:

• Does key == x[0]? • Does key == x[1]? • Does key == x[2]? etc.

• If key matches x[i] for some index i, the search terminates and returns array index i, the index of the cell of the array where key resides.

• If key is not found in the array, the search returns -1 or some other value indicating a failure to locate key.

 

Page 44: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Linear Search

1. public static int search(int[] x, int n, int key) 2. {3. // returns the position of key in x4. // if key is not found returns -15. // the array x may be partially filled; n is the number of data in x6.  7. for ( int i = 0; i < n; i++)8. if (key == x[i]) // key is found9. return i; // return the index10. return -1; // key is not found11.  12. }

Page 45: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Binary Search

• A search routine that performs much better than linear search is binary search.

• Binary search requires that the array be sorted.

• To search an array x, for key, binary search first compares key to the item situated in the middle of the array, say x[mid].

• If key equals x[mid], the search ends successfully.

• If key < x[mid], then x[mid] and all elements greater than x[mid] are eliminated from the search.

• If key > x[mid], then x[mid] and all items less than x[mid] can be eliminated.

• Thus after examining a single location, half of the data in the array can be eliminated from the search.

• Binary search repeats this process on the part of the array that has not yet been eliminated until the key is located or there are no more items to examine.

Page 46: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Binary Search

• Search for the key 27 in the sorted array:  

[3 5 6 9 11 23 25 26 27 29 33 35 36 37 39 42 45 46 48 58 62 67 70]. • Binary search first compares 27 to the middle item of the

array, which is 35.

• Because 27 is less than 35 and the array is sorted, the “sub-array” [35 36 37 39 42 45 46 48 58 62 67 70] can be eliminated from any further searching.

• If 27 is on the list, then 27 must be situated in the “sub-array” [3 5 6 9 11 23 25 26 27 29 33].

Page 47: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Binary Search

After one comparison , half the array is eliminatedNext, binary search compares the key (27) to the middle element of this sub-array:

Page 48: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Binary Search

Binary search after two comparisons

Page 49: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Binary Search

Since 27 is greater than the middle element (23), binary search now searches those values greater than 23.

The key is foundThe key value 27 is located after examining just three locations.

Page 50: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Binary Search

1. static int search(int[] x , int n, int key)2. // x is a sorted array of n integers; key has an integer value3. //x is sorted in ascending order; 4. {5. int lo = 0; // lowest index of the array6. int hi = n-1; // highest index 7. int mid; // middle index8. while (hi >= lo) 9. {10. mid = (hi + lo)/2; // get the middle index11. if (key == x[mid])12. return mid; //key found --exit13. if (key < x[mid])14. hi = mid - 1; //eliminate x[mid] thru x[hi]15. else16. lo = mid + 1; // eliminate x[lo] thru x[mid]17. }18. return -1; // key not found19. }

Page 51: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Binary search in action. key = 27; blocks in gray are eliminated from the search

Iteration 1 Iteration 2 Iteration 3lo = 0; hi = 22; mid = 11 lo = 0; hi = 10; mid = 5 lo= 6; hi = 10; mid = 8

Adjust hi : hi = mid-1 Adjust lo: lo = mid+ 1 Return 8 – index of the key

.

Page 52: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Binary Search

• For a list of n items, linear search, on average, examines n/2 locations.

• Binary search checks only about log2 n – 1 locations: n n/2 (linear search) log2n –1 (binary search) 210 =1024 512 9215 =32768 16384 14220 =1048576 524288 19225 =33554432 16777216 24

Page 53: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Two-Dimensional Arrays

1% 2% 3% 4% 5% 6%10 years 1.10 1.22 1.34 1.48 1.63 1.7915 years 1.16 1.35 1.56 1.80 2.08 2.4020 years 1.22 1.49 1.81 2.19 2.65 3.2125 years 1.28 1.64 2.09 2.67 3.39 4.2930 years 1.35 1.81 2.43 3.24 4.32 5.74

• A two-dimensional array holds tabular data:

• The values stored in a two-dimensional array must all be of the same data type.

• Each storage cell in the table is uniquely identified by its row and by its column. The rows and columns of a two-dimensional array are indexed starting at 0.

Page 54: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Two-Dimensional Arrays

X is located in row 3, column 1

Page 55: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Two-Dimensional Arrays

A 2 × 2 array, and a 3 × 2 arrayEach cell in a two-dimensional array can be accessed using its row and column number. The cell A[i][j] is the cell of row i and column

j. .

Page 56: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Two-Dimensional Arrays

Each cell has can be accessed with two indices

Page 57: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Declaring and Instantiating Two-Dimensional Arrays

The statement:int[][] table;

declares table to be a reference to a two-dimensional array of integers.

Two-dimensional instantiation includes the number of rows as well as the number of columns, in that order:

  table = new int[2][3]; // table has 2 rows and 3 columns

int[] table = new int[2][3];

Page 58: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Two-Dimensional Arrays

• Declaration and instantiation can be done with a single statement:

int table = new int[2][3];

• The new operator creates a 2 × 3 two-dimensional array with all cell values initialized to 0.

Page 59: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Two-Dimensional Arrays

• Although it is intuitive to view a two-dimensional array as a simple table, the underlying structure is more complex.

 • A two-dimensional array is actually an “array of arrays.”

An array of arraysIt is easier to visualize a two-dimensional array as a simple table or grid

A two-dimensional array pictured as a table or grid

Page 60: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Processing a Two-Dimensional Array

int A[][] = new int[3][4]; // declares and instantiates a 3 × 4 array for (int row = 0; row < 3; row++) // for each row for (int col = 0; col < 4; col++) // for each column

A[row] [col] = row*col;

row = 0 col = 0 A[0][0] = 0 col = 1 A[0][1] = 0 col = 2 A[0][2] = 0 col = 3 A[0][3] = 0

row = 1 col = 0 A[1][0] = 0 col = 1 A[1][1] = 1

col = 2 A[1][2] = 2 col = 3 A[1][3] = 3

row = 2 col = 0 A[2][0] = 0 col = 1 A[2][1] = 2

col = 2 A[2][2] = 4 col = 3 A[2][3] = 6

The loops work as follows:

0 0 0 00 1 2 30 2 4 6

Array initialized with nested loops

Page 61: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Processing a Two-Dimensional Array

• A two-dimensional array can be explicitly initialized in a declaration by listing the values of each row enclosed by curly braces and separated by commas:

int[][] table = { {2,4,6} {8,10,12} };

 

An array explicitly initialized in its declaration

Page 62: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Processing a Two-Dimensional Array

Reading data into a two dimensional array:

Scanner input = new Scanner(System.in);int [][] a = new int[5][4];for (int row = 0; row < 5; row++) for (int col= 0; col < 4; col++)

a[row][col] = input.nextInt();

Displaying the contents of a, row by row:

for ( int row = 0; row < 5; row++) // for each row{ for (int col = 0; col < 4; col++) //for each column

System.out .print (a[row][col] + “ “); // print the column value System.out.println(); // a newline for the next row}

Java allows arrays of dimension higher than two. A three-dimensional array:

int[][][] threeD;threeD new int[3][4][5];for (int i = 0; i < 3; i++) for (int j = 0; j < 4; j++) for (int k = 0; k < 5; k++)

threeD[i][j][k] = i*j*k;

Page 63: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Processing a Two-Dimensional Array

Example:

• A contingency table is a two-dimensional grid often used as an aid for analyzing the relationship between two variables.

• For example, a researcher interested in whether or not a relationship exists between gender and music preference surveyed 1000 people with the following results:

• The numbers in the last column and last row are not part of the collected data.

• These are the row totals and the column totals.

• The number in the bottom right corner is the grand total, the sum of all data. 

Rock Heavy Metal Folk Jazz R& B Pop Country Other TotalMales 123 145 33 34 16 71 18 42 482Females 138 112 50 27 93 75 10 13 518Total 261 257 83 61 109 146 28 55 1000

Page 64: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Processing a Two-Dimensional Array

Problem Statement: • Write an application that queries a user for the number of rows and columns of a

contingency table, reads the data, row by row, and displays the data in tabular form along with the row totals, column totals, and grand total.

 For example, if the 6 data of a 2×3 table are:

1, 3, 6, 7, 9, and 8,

the program displays these 6 numbers together with the appropriate totals as:

1 3 6 | 107 9 8 | 24

 8 12 14 | 34

 10 and 24 are row totals, 8, 12, and 14 the column totals, and 34 the grand total.

• The “|” character is used to separate the data from the row totals.

Page 65: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Processing a Two-Dimensional Array

The solution utilizes three methods: • readData (...) fills a two-dimensional array with data supplied

by the user. The data is entered row by row.

• display(...) prints the table along with the row, column, and grand totals.

• getTotals(...) calculates the row totals, and the column totals.  

Page 66: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

readData

import java.util.*; 1. public class ContingencyTable2. {3. public static void readData( int[][] table, int numRows, int numCols)4. {5.  6. // reads the data for a table row by row7. // the table has rows rows and cols columns8.  9. System.out.println("Enter data, row by row: ");10. Scanner input = new Scanner(System.in);

11. // read data , row by row12. for (int row = 0; row < numRows; row++) 13. for (int col = 0; col < numCols; col++)14. table[row][col] = input.nextInt();

15. }

Page 67: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

display

16. public static void display(int table[][], int numRows, int numCols, int[] rowSums, int[] colSums)

17. {18. // displays the contingency table19. // displays row and column totals and grand total20. System.out.println();21. System.out.println();22. System.out.println("Data including row and column totals: ");23. System.out.println();24. // print the table row by row25. // after printing a row, print the row total26. for(int row = 0; row < numRows; row++) // for each row27. {28. for (int col = 0; col < numCols; col++) // for each column29. System.out.print(" "+table[row][col]+"\t");30.  31. System.out.println("| "+rowSums[row]); // print the row total32. }

Page 68: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

display

33. System.out.println();34. int grandTotal = 0;35. // calculate the grand total from the column sums36. // print the column sums then the grand total37. for (int col = 0; col < numCols; col++) // for each column38. {39. grandTotal += colSums[col]; //add column sum to grandTotal40. System.out.print(" "+colSums[col]+"\t"); //print column sum41. }42. System.out.println("| "+grandTotal);43. } 

Page 69: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

getTotals

44. public static void getTotals(int[][]table, int numRows, int numCols, 45. int[] rowSums, int [] colSums)46. {47. //calculates the row sums and column sums48. // get row sums49. for (int row = 0; row < numRows; row++) // for each row50. for (int col = 0; col< numCols; col++) // for each column51. rowSums[row] += table[row][col]; // add the table entry to

// the row sum52. // get column sums53. for (int col = 0; col < numCols; col++) // for each column54. for (int row = 0; row< numRows; row++) // for each

row55. colSums[col] += table[row][col]; // add the table entry to

// the column sum56. } 

Page 70: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

main

57. public static void main(String[] args)

58.{59. Scanner input = new Scanner(System.in);60. int rows, cols; // dimensions of the table61. int[][] table; // contingency table62. int[] rowSums; // holds the row totals63. int colSums[]; // holds the column totals64. System.out.print("Number of rows: " );65. rows = input.nextInt();66. System.out.print("Number of columns: ");67. cols= input.nextInt();68. table = new int[rows][cols];69. rowSums = new int[rows];70. colSums = new int[cols];71. readData(table, rows, cols);72. getTotals(table, rows, cols, rowSums, colSums); // calculate the sums73. display(table, rows, cols, rowSums,colSums);74. }75. }

Page 71: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Output

Number of rows: 2Number of columns: 8Enter data, row by row:123 145 33 34 16 71 18 42 138 112 50 27 93 75 10 13 Data including row and column totals:  123 145 33 34 16 71 18 42 | 482 138 112 50 27 93 75 10 13 | 518  261 257 83 61 109 146 28 55 | 1000

Page 72: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Discussion

Lines 4 – 14: void readData( int[][] table, int numRows, int numCols)

• The nested loop on lines 11-13 iterates through the table row by row.

• If the table has 2 rows and 3 columns, the nested loop runs through the indices of the array in the following order:

[0,0] [0,1] [0,2] // row = 0, col = 0,1,2[1,0] [1,1] [1,2] // row = 1, col = 0,1,2

 

Page 73: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Discussion

Lines 15 – 41: display (int table[][], int numRows, int numCols, int[] rowSums, int[] colSums)

• The nested loop on lines 25-30 iterates through the table row by row. Before incrementing the loop counter row the method prints a separator character (‘|’) followed by the row total. The data of each row is printed, followed by the separator, followed by the row total. If the table consists of two rows and three columns, printing proceeds:

[0,0] [0,1] [0,2] rowSum[0] // row = 0, col = 0,1,2 [1,0] [1,1] [1,2] rowSum[1] // row = 1, col = 0,1,2

Page 74: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Discussion

• The single loop on lines 35-39, which iterates through the columns:

• adds each column sum to the grand total ( line 37), and• prints each column sum (line 38).

 • The statement on line 40 prints the separator and the grand

total.

Page 75: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Discussion

Lines 42 – 53: void getTotals(int[][]table, int numRows, int numCols, int[] rowSums, int[] colSums)

• This method calculates values stored in the two one-dimensional arrays, rowSums and colSums

• The nested loop on lines 46-48, iterates through the table, row by row.

• For each row, the corresponding column value is added to the row total.

   

Page 76: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

If table is a 2×3 array, the calculation proceeds as follows: 

Initially rowSum[0] and rowSum[1] have value 0

row = 0 col = 0 rowSum[0] += table[0][0] col = 1 rowSum[0] += table[0][1] col = 2 rowSum[0] += table[0][2]

row = 1 col = 0 rowSum[1] += table[1][0] col = 1 rowSum[1] += table[1][1] col = 2 rowSum[1] += table[1][2]

Page 77: Java Programming: From the Ground Up  Chapter 7 Arrays and Lists: One Name for Many Data

Index out of Bounds

The infamous “array index out of bounds” error.

• An array x of length n is indexed from 0 to n-1.

• An attempt to access x[n] or x[x.length] results in a runtime error, that is, one that occurs during the run of the program and terminates the program.

• When using a for loop to process x, the correct form is:

for (int i = 0; i < x.length; i++)

and not

for (int i = 0; i <= x.length; i++)