Docstoc

General

Document Sample
General Powered By Docstoc
					        One-Dimensional (1-D) Array

                    Overview

   Why do we need 1-D array

   1-D array declaration and Initialization

   Accessing elements of a 1-D array

   Passing Array as parameter

   Some Examples of Array processing

   Preview: More on 1-D Arrays




                                               1
     Why do we need data 1-D array?
Why do we need data 1-D array?
 There are many applications where several data
  values are needed in the memory at same time.
 Example, counting number of students who
  perform below average in a class of 30.
 Obviously we need to scan through the list of
  values two times;
   » first to compute the average and
   » second to count those below average.
 To solve this problem, do we need to declare 30
  variables or do we read the values the second time?
 Both of these solutions are not convenient
 This is even more so when data size is expected to
  grow very larger.
 One convenient solution to this and similar
  problems is array.
 An array is a contiguous list of memory cells that
  can be identified using a single variable.


                                                 2
                   Array Declaration
   An array is declared as shown below
    int[] grades = new int[10];

   Another way to declare array, which is not as readable as
    above is:
    int grades[] = new int[10];

   Each of the above methods declares an int array of size 10
    which cab be shown as a diagram as below, but we
    discourage the use of the second method:
    grades                   Array object
    reference
                Index    0 1     2 3 4 5         6 7 8 9
   Other examples of array declaration are shown below. Notice
    that the last example where two arrays are declared at the
    same time is discouraged.

    float[] prices = new float[500];

    boolean[] flags;
    flags = new boolean[20];

    char[] codes = new char[1750];
    int[] first = new int[100],
           second = new int [200];
                                                                3
                 Bounds Checking
• Once an array is created, it has a fixed size
• Each array object has a public instance variable
  called length that stores the size of the array
• The length of an array object is referenced through
    the array name just like any other object:
              grades.length

• An index used in an array reference must specify a
    valid element -- must be in the range 0 to N-1 for
    an array of N elements, otherwise, the exception
    ArrayIndexOutOfBoundsExecption is thrown.
•   Thus, the Java interpreter is said to exhibit
    automatic bounds checking.




                                                    4
                  Initializer List
• An initializer list can be used to instantiate and
  initialize an array in one step
• The values are delimited by braces and separated
  by commas as shown below

 int[] units = {147, 323, 89, 933, 540,
               269, 97, 114, 298, 476};

  char[] letterGrades = {'A', 'B', ‘C’
                          'D', 'F'};

• Notice that in the above examples, it is actually the
  compiler that fills the gap. Thus, in the first
  example, the compiler would do the following:

  int[] units = new int[10];
  units[0]=147; units[1]=323; ...;
  units[9]=476;


• Observe that when an initializer list is used:
   • the new operator is not used
   • the size is not specified
                                                    5
        Accessing elements of an Array
• A particular cell in an array can be referenced using
    the array name followed by the index of the cell in
    brackets.
•   For example, the following statement stores 20 in
    the cell whose index is 4 (cell number 5)
                  grades[4] = 20;
    grades                Array object
    reference                        20
                Index   0 1   2 3 4       5 6 7 8 9
• The following example demonstrates array index
    processing. Each cell is initialized to zero.
 class FillOneDArray {
     public static void main (String args[]) {
         int[] grades = new int[10];
         for (int i=0; i < grades.length; i++)
             grades[i] = 0;
     }
  }


• Notice that the only modification needed for the
    above function to handle a different array size, say
    20, is in line 3. The loop remains the same.


                                                     6
            Passing Array as a parameter
   An entire array can be passed to a method as a
    parameter
   Like any other object, the reference to the array is
    passed, making the formal and actual parameters
    aliases of each other
   Changing an array element in the method changes
    the original
class ParameterPassingExample {
   public static void main(String [] args){
    int i;
    int [] a = {1, 2, 3, 4};
    double d = 5.5;

        System.out.println("After initialization");
        for (i = 0; i < a.lenght; i++)
          System.out.println("a["+i+"]="+a[i]);
        System.out.println("d = " + d);
        System.out.println("Calling tryToChange.");
        tryToChange(a, d);
        System.out.println("Back from tryToChange");
        for (i = 0; i < a.length; i++)
          System.out.println("a["+i+"]="+a[i]);
        System.out.println("d = " + d);
    }
                                                       7
        Passing Array as a parameter (cont’d)
        private static void tryToChange(int [] arr,
                         double dd) {
        int i; dd = 3.14;
        arr[0] = 55; arr[3] = 100;
        for (i = 0; i < 4; i++)
         System.out.println("arr["+i+"]="+arr[i]);
        System.out.println("dd = " + dd);
    }
          After initialization Back from tryToChange
}
          a[0]= 1               a[0]= 55
          a[1]= 2               a[1]= 2
          a[2]= 3               a[2]= 3
          a[3]= 4               a[3]= 100
          d = 5.5               d = 5.5
          Calling tryToChange
           arr[0]= 55
           arr[1]= 2
           arr[2]= 3
           arr[3]= 100
           dd = 3.14
                                                      8
More examples: What if size is unknown?
  It is important to note that the size of the array must
   be determined before it can be created.
 Thus, if we do not know the exact size of data, the
   only option is create an array of reasonably large
   size and hope that the actual data will not be up to
   that.
 In such case, we need to have an accompanying
   variable that keep count of the actual data stored in
   the array.
 The following example reads grades from the user
   until –1 is entered and prints the average grade and
   those grades below average.
import java.io.*;
class ArrayGrades {
 public static void main(String[] args) throws
   IOException {
   BufferedReader stdin = new BufferedReader(
   new InputStreamReader(System.in));
   int numGrades=0;
   double[] grades = new double[100];
   double sum = 0, average, grade;
                                                     9
More examples: What if size is unknown?
     do {
       System.out.print("Enter Next Grade: ");
        grade = Double.parseDouble(stdin.readLine());
        if (grade >= 0) {
            grades[numGrades] = grade;
            sum += grade;
            numGrades++;
         }
       } while (grade >= 0);
       if (numGrades > 0) {
          average = sum / numGrades;
          System.out.println("The average = " +
      average);
          System.out.println("Those below average
      are: ");
          for (int i=0; i<numGrades; i++)
             if (grades[i] < average)
                 System.out.println(grades[i]);
      }
 }
}
                                                10

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:8
posted:8/12/2012
language:
pages:10