Chapter 8 - Arrays and Array Processing

Chapter Objectives:

You should be able to:

  • Use array data structures.
  • Solve problems that require collections of data.
  • Sort an array of data.
  • Demonstrate your understanding of sequential and binary search algorithms.
  • Demonstrate your understanding of inheritance and polymorphism.

Index:

Introduction

One Dimensional Arrays

Declaring and creating an Array

Creating an array of objects (e.g. String)

Creating an Array of CyberPets

Initializing Elements

Passing arrays as arguments to methods

Example: Store the First 100 Squares (figure 8-6)

public class Squares {
    static final int ARRSIZE = 100;           // The array's size
    static int intArr[] = new int[ARRSIZE];   // Create an int array

    public static void main(String args[]) {
        for (int k = 0; k < intArr.length; k++)  // Initialize the array
            intArr[k] = (k+1) * (k+1);

        System.out.print("The first 100 squares are"); // Print heading
        for (int k = 0; k < intArr.length; k++)
        {      // Print the array
            if (k % 10 == 0)
                System.out.println(" ");        // 10 elements per row
            System.out.print( intArr[k] + " ");
        } // for
    } // main()
} // Squares

Program Output:

The first 100 squares are
1 4 9 16 25 36 49 64 81 100
121 144 169 196 225 256 289 324 361 400
441 484 529 576 625 676 729 784 841 900
961 1024 1089 1156 1225 1296 1369 1444 1521 1600
1681 1764 1849 1936 2025 2116 2209 2304 2401 2500
2601 2704 2809 2916 3025 3136 3249 3364 3481 3600
3721 3844 3969 4096 4225 4356 4489 4624 4761 4900
5041 5184 5329 5476 5625 5776 5929 6084 6241 6400
6561 6724 6889 7056 7225 7396 7569 7744 7921 8100
8281 8464 8649 8836 9025 9216 9409 9604 9801 10000

Random Number Generation

int coinFlip = (int)(Math.random() * 2);

int coinFlip = (int)(Math.random() * N);

int die = 1 + (int)(Math.random() * 6);

M + (int)(Math.random() * N);

Example: Simulating throwing a Die

public void testDie(int nTrials) {
   int die; // Represents the die
   for (int k = 0; k < nTrials; k++) { // For each trial
       die = 1 + (int)(Math.random() * NFACES); // Toss the die
       ++counter[die - 1]; // Update the appropriate counter
     } // for
} //testDie()


View complete TestDie application code.

CyberPet Animation


Array Algorithm : Sequential Search

Array Algorithms : Sorting

30 3 45 -6 15 //first pass

3 30 -6 15 45 //second pass

3 -6 15 30 45 //third pass

-6 3 15 30 45 //fourth pass

public void swap(int arr[], int el1, int el2) {
     int temp = arr[el1];
//assign the first element to temp
     arr[el1] = arr[el2]; //overwrite first with second
     arr[el2] = temp; //overwrite second with first (temp)
    
} // swap()

View Bubble Sort code

Selection Sort Algorithm

Algorithm:

  1. For count = 1 to 51
  2.   smallest card = count
  3.   For currentCard = count+1 to 52
  4.     If deck[currentCard] < deck[smallestCard]
  5.       smallestCard = CurrentCard
  6.   If smallestCard != count
  7.     Swap deck[count] and deck[smallestCard]

Binary Search

Example: find out if "7" is in the array {100, 6, 55, 7, 15, 40}

intArr[0]

intArr[1]

intArr[2]

intArr[3]

intArr[4]

intArr[5]

100

6

55

7

15

40

6

7

15

40

55

100

low

 

mid

   

high

low

mid

high

     

 

View Search Class

View TestSearch code


Two Dimensional Arrays

Initializing Two Dimensional Arrays

Example:  Calculate average rainfall

Example: Calculate average rainfall for a particular month

/**
  * Computes average rainfall for a given month
  * @param monthRain is a 1D-array of rainfalls
  * @param nDays is the number of days in monthRain
  * @return The sum of monthRain / nDays
  * Pre:  1 <= nDays <= 31
  * Post: The sum of monthRain / nDays is calculated
  */

public double avgRainForMonth(double monthRain[], int nDays) {
     double total = 0;
     for (int day = 1; day < monthRain.length; day++)
         total = total + monthRain[day];
     return total/nDays;
} // avgRainForMonth()

 

to call...

   double rainfall[][] = new double[13][32];

  double marchAvg = avgRainForMonth(rainfall[3], 31);  // this passes a reference to a single row in the array


Summary


Keywords:

array, array initializer, array length, binary search, bubble sort, element, element type, multidimensional array, one-dimensional array, polymorphic method, pseudorandom number, random , number scaling, selection sort, sequential search, sorting, subscript
 

Suggested Exercises:  1, 2, 3, 4, 5, 7, 8, 9, 12, 14, 15, 17, 29