INFORMATION & COMPUTER SCIENCE DEPARTMENT, KFUPM

ICS102, SECTIONS 52, 54 & 55  (001 Semester)

INTRODUCTION TO COMPUTING

LAB  #11 Arrays

 

Instructor: Bashir M. Ghandi

 


Objectives:

To gain experience with:

 

1.  Declaration and Creation of Array & accessing array elements

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.  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.

 

 

An array is declared as shown below

      int[] grades = new int[10];  //recommended

or

      int grades[] = new int[10];  // not recommended

 

The above can also be broken into two steps:

1.             Declaration of the array:     int[] grades;

 

This declares a reference variable for an integer array (a variable that can hold the address of an integer array).

grades

 

 

2.             Creation of the array:           grades = new int[10]; 

 

This creates the array in the memory (just like any object) and stores its address in the reference variable grades.

grades

 

 

 

 

 

 

 

 

 

 

 

address of array

 

 

 

 

 

 

 

 

 

 

index

 

0

1

2

3

4

5

6

7

8

9

 

Notice that the index of an array begins from zero and ends one less than the size.  Any attempt to access elements outside this range will make the java interpreter to throw ArrayIndexOutOfBoundsException.

 

Once an array is created, its individual elements can be accessed by using the array name followed by the index in square brackets.  Example, to assign 15 to element number 6, we write:

grades[5] = 15;

 

Each array has an instance final variable length that holds the size of the array.  This is very useful if we need to access each element of the array.  For example, the following for loop initializes each element of the array to its index:

 

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

      grades[i] = i;

 

If we have the values to be assigned to an array are known, then an array can be created using initializer list as follows:

char[] vowels = {‘a’,  ‘e’,  ‘i’, ‘o’,  ‘u’}

 

This declares and creates a character array of five elements and initializes it with the vowel characters.  Notice that in this case, the size is not specified and the new operator is not used.  The compiler automatically counts the elements, creates an array of the appropriate size and fills the array with the elements. 

 

Finally, 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.

Example 1: 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.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
 
class ArrayGrades {
 
  static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
 
  public static void main(String[] args) throws IOException {
 
    int numGrades=0;             
    double[] grades = new double[100];
    double sum = 0, average, grade;
 
    do { 
        System.out.print("Enter Next Grade: ");
        grade = Double.parseDouble(stdin.readLine());
        if (grade >= 0) {
           grades[numGrades] = grade; 
            sum += grade;
            numGrades++;
        }
    } while (grade >= 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]);
  }
}

 

2.  Arrays can be passed as parameters to method, also a method can return array result.

An array, like any object, can be passed to a method as parameter.  In that case, the reference to the array is passed to the method.  Thus, the method can change the content of the actual array.  Similarly, a method can return an array reference.

 

Example 2: The following example uses methods to read two arrays from the user and prints their dot product.

import TextIO;
import java.io.IOException;
 
class ArrayAndMethods {
  static TextIO stdin = new TextIO(System.in);
 
  public static void main(String[] args) throws IOException {
        int size;
        System.out.print("Enter array size: ");
        size = stdin.readInt();
        
        double[] firstArray = createArray(size);
        double[] secondArray = createArray(size);
        System.out.println("The dot product = "+dotProduct(firstArray, secondArray)); 
  }
  
  static double[] createArray(int size) throws IOException {
          double[] array = new double[size];
          System.out.println("Enter "+size+" elements for this array: ");
          for (int i=0; i<size; i++) 
                array[i] = stdin.readDouble();
          
          return array;
  }
  
  static double dotProduct(double[] first, double[] second) {
           double sum = 0;
           for (int i=0; i<first.length; i++)
               sum += first[i]*second[i];
 
           return sum;
  }
}

 

3.  Arrays of objects.

The arrays we have seen so far have all been arrays of primitive types.  The next example shows that arrays of objects can also be created.

 

Example 3: 

import TextIO;
import java.io.IOException;
 
class Student {
        int iDNumber;
        double grade;
        
        public Student(int iDNumber, double grade) {
               this.iDNumber = iDNumber;
               this.grade = grade;
        }
        
        public void print() {
               System.out.println(iDNumber+"\t"+grade);
        }
}
        
public class ArrayOfObjects {
  static TextIO stdin = new TextIO(System.in);
 
  public static void main(String[] args) throws IOException {
        int size;
        System.out.print("Enter number of students: ");
        size = stdin.readInt();
        
        Student[] students = createArray(size);
        double average = average(students);
        System.out.println("The average is "+average);
        
        System.out.println("Students below average are");
        for (int i=0; i<students.length; i++)
           if (students[i].grade < average)
               students[i].print(); 
  }
  
  static Student[] createArray(int size) throws IOException {
          Student[] array = new Student[size];
          int id;
          double grade;
          System.out.println("Enter "+size+" students");
          
          for (int i=0; i<size; i++) {
                System.out.print("ID Number : ");
                id = stdin.readInt();
                System.out.print("Grade : ");
                grade = stdin.readDouble();
                
                array[i] = new Student(id, grade);
          }
          return array;
  }
  
  static double average(Student[] studentList) {
           double sum = 0;
           for (int i=0; i<studentList.length; i++)
               sum += studentList[i].grade;
 
           return sum/studentList.length;
  }
}

 

4.  Two-dimensional arrays

A two-dimensional array is declared in a similar manner to 1-D array but with the addition of one more bracket as in the following example;

      int [][] a = new int[3][4];

 

a

0

1

2

3

0

 

 

 

 

1

 

 

 

 

2

 

 

 

 

 

Although it is convenient to think of a 2-D array as a table as shown above, in reality, it is an array of array references. 

The following figure shows how a is actually represented.

The elements are accessed by using the array name followed by the row and column, each in square brackets. Example, the statement:

a[2][1] = 5;

 

assigns 5 to the cell at third row, second column.

a

0

1

2

3

0

 

 

 

 

1

 

 

 

 

2

 

5

 

 

 

Example 4:  The following example reads two 2-D arrays, compute their sums and print the result.

import TextIO;

import java.io.IOException;

 

public class Matrix {

 

  static TextIO stdin = new TextIO(System.in);

 

  public static void main(String[] args) throws IOException {

      int row, column;

      System.out.print("Enter number of rows: ");

      row = stdin.readInt();

      System.out.print("Enter number of columns: ");

      column = stdin.readInt();

     

      double[][] a = createArray(row, column);

      double[][] b = createArray(row, column);

      double[][] c = sum2DArray(a,b);

      System.out.println("The sum of the two arrays is");

      print2DArray(c);

  }

 

  static double[][] createArray(int row, int col) throws IOException {

        double[][] array = new double[row][col];

 

        System.out.println("Enter elements for a "+row+" by "+col+" matrix");

        

        for (int i=0; i<row; i++)

            for (int j=0; j<col; j++)

                  array[i][j] = stdin.readDouble();

           

        return array;

  }

 

   static double[][] sum2DArray(double[][] a, double[][] b) {

        int row = a.length;

        int col = a[0].length;

        double[][] c = new double[row][col];

 

        for (int i=0; i<row; i++)

            for (int j=0; j<col; j++)

                  c[i][j] = a[i][j] + b[i][j];

           

        return c;

  }

 

  static void print2DArray(double[][] a) {

        int row = a.length;

        int col = a[0].length;

 

        for (int i=0; i<row; i++) {

            for (int j=0; j<col; j++)

                  System.out.print(a[i][j]+ "\t");

            System.out.println();

        }  

  }

}

 

 

5.  Assignments

1.       Modify example 2 (ArrayAndMethods) above by adding the following methods:

·         prints1DArray:  that prints a 1-D array passed to it as a parameter on one line.

·         sum1DArray: that receives two 1-D arrays as parameters and returns an array whose elements are the sum of the corresponding elements of the arrays received as parameters.

·         equals: that returns true if all the corresponding elements of two 1-D arrays passed to it as parameters are equal.

·         reverse that reverses the elements of a 1-D array received as parameter

 

      Test your methods by adding statements in the main method to do the following:

·         print the sum of the two arrays

·         check if the two arrays are equal and print an appropriate message.

·         print the reverse of the first array.

2.        Modify example 4 (Matrix) above by adding the following methods:

·         scalerProduct: that receives a matrix and a number and returns a matrix obtained by multiplying each element of the matrix received as parameter by the number.

·         equals: that returns true if all the corresponding elements of two 2-D arrays passed to it as parameters are equal

 

      Test your methods by adding statements in the main method to do the following:

·         print the result of taking the scalar product of the first matrix by 5

·         check if the two matrices are equal and print an appropriate message.

3.        Modify example 3 (ArrayOfObjects) above by adding the following methods:

·         max: that receives an array of student objecst and return the student with the height grade.

·         min: that receives an array of student objects and return the student with the lowest grade

 

      Test your methods by adding statements in the main method to do the following:

·         print the student with the highest grade

·         print the student with the lowest grade