Unit 4

Arrays

In the programs we have written so far, each variable was associated with a single memory cell. These variables are called simple variables, and their data types are simple ones. The only exceptions were file variables that were associated with a collection of characters stored on a disk.

When you want to handle sets of values of the same type-the first 100 squares, for example - you really don't want to have to name them individually. What you need is an array.

An array is a named set of variables of the same type. Each variable in the array is called an array element. To reference a particular element in array, you use the array name combined with an integer value called and index. The index for an array element is the offset of that particular element from the beginning  of the array. The first element will have an index of 0. The second element will have and index of 1, the third an index of 2 and so on.

 

Declaring and Creating Arrays

The following command declares an array variable:

int squares [ ] ;    // declares an integer array variable

Once you have declared an array variable, you can define an array that it will reference:

squares = new  int [10];  // define an array of 10 integers

You are not obliged to create an array  itself when you declare the array variable. You could also declare the array variable, and define the array of type integer to hold 10 square numbers with a single statement:

        int squares[ ] = new int[10];

       

Initializing Arrays

You can initialize an array with your own value when you declare it, and thus determine how many elements it will have.

int squares[ ] = {1, 4, 9, 16, 25};

If you want to set some of the array elements to values explicitly, you should use an assignment statement for each element.

        int squares [ ] = new int [100];

        squares [0] = 1;

        squares [1] = 4;

Time to Practice

Let's write a simple program that creates a string array of 9 elements to store the names of the students in our ICS4M class.

 /*The Array1 Program
 * Programmed by: Mr. J. Augustine, April 2004
 * This program prompts for the names of the students
 * in the ICS4U class and enter these name into an array.
* Then it displays the contents of the array elements.
*/
import javax.swing.JOptionPane;
public class Array1 {
public static void main(String[] args) {

String names[] = new String[9];//Declares a new array of size 9 to hold string values

for(int i=0; i<9; i++){
//To initialize the array with the names
names[i]= JOptionPane.showInputDialog("Please enter the name:");
}//end of for loop

System.out.println("Names of Students");//Title of the list

// For loop to print the contents of the array
for(int i=0; i<9; i++){
System.out.println(names[i]);
}// end of for loop
System.exit(0);
}// end of main method
}//end of class

Now, let's write a program to get Computer Science marks of the students in the ICS4M class and store them in an integer array of 9 elements.

/**The Array2 Program
* Programmed by: Mr. J. Augustine, April 2004
* This program prompts for Computer Science marks of each student in the ICS4M class.
* It stores the marks in an integer array and displays the marks list.*/


import javax.swing.JOptionPane;
public class Array2 {

public static void main(String[] args) {
// A string array to of 9 elements initialized with the names of the students
String names[] ={"Ashley", "Khalis", "Reva", "Vicknesh", "Chan", "Mark", "JinHong", "Sue Yen", "vivian"};

int marks[] = new int[9];// Declares an integer array to store the marks

//For loop to prompt for the 9 marks
for(int i=0; i<9; i++){
marks[i]=Integer.parseInt(JOptionPane.showInputDialog("Please enter the marks of "+ names[i]));

}// end of for loop

System.out.println("\tName\t\tMarks");//Prints the title
//For loop to display the contents of the array marks
for(int i=0; i<9; i++){
System.out.println("\t" + names[i]+"\t\t"+ marks[i]);
}// end of for loop
System.exit(0);
}// end of main method
}// end of class

This program add the integers stored in a array of ten elements.


/*The Array3 program
*Programmed by: Mr. J. Augustine, April 2004
*This program add the ten numbers stored in an array
*and display the result on the screen */

public class Array3 {

public static void main(String [] args){
// array is initialized with 10 integers
int array[] = {45, 34, 25, 67, 56, 78, 56, 96, 25, 68};
int sum=0; //To store the total

//For loop to add the ten numbers
for (int i=0; i<10; i++){
sum += array[i];
}//end of for loop

//Prints the result on the screen
System.out.println("The sum of the ten elements in the array is "+sum);
}// end of main method
}// end of class

 

This program demonstrate how the data in one array can be used as the subscript on another array.

/*The Array4 Program
*Programmed by: Mr. J. Augustine, April 2004
*This program displays the frequence distribution of
*the response of 50 students in a survey. */

public class Array4 {
public static void main(String[] args) {

//This array is initialized with the 50 responses
int surveyResponse[] ={1, 3, 6, 4, 9, 8, 10, 7, 6, 5, 4, 5, 6,
5, 8, 6, 4, 8, 5, 2, 2, 8, 7, 9, 8, 7, 9,
4, 5, 8, 6, 3, 7, 6, 7, 6, 9, 10, 5, 6, 2,
4, 2, 7, 8, 9, 8, 5, 7, 6 };

int frequency[] = new int[10];// Holds the frequency of each response

for(int i=0; i<10; i++){
frequency[i]=0; // each element is initialized to 0
}//end of for loop

//For loop to calculate the frequency
for(int i=0; i<50; i++){
frequency[surveyResponse[i]-1] ++;
}//end of for loop

//Prints the title of the frequency table
System.out.println("\tResponse\tFrequency");

//This for loop prints the frequency distribution
for(int j=0; j<10; j++){
System.out.println("\t"+(j+1)+"\t"+frequency[j]);
}
}//end of main method
}//end of class

Methods and Arrays

In Java, parameters of primitive data types are passed to methods by value.  This means that the value is sent to the method and stored in another temporary variable.  If that variable is changed INSIDE the method, the change will not be maintained in the main method.  In other words the value of the original variable will not change.  Consider the following program.

/* The Array5 Program
*Programmed by: Mr. J. Augustine, April 2004
*This program demonstrates that variable parameters are passed by value and are
*not changed by the receiving method.*/

public class Array5{

    public static void main (String[ ]args){
        //The main method, the program begins here
        int num = 7;
        System.out.println("The value of num is before being passed as a parameter to a method is: " + num);
        doesNothing (num);
        System.out.println();
        //The variable num is being passed to the method doesNothing by value
        System.out.println("The value of num after being manipulated by a method is still: " + num);
        //When this prints out to the screen you can see that the value
        //of the variable has not changed after being used in the method
        //doesNothing
    }//end main

    public static void doesNothing(int number){
        //This method receives a copy of the variable and can
        //manipulate it in any way without changing the original
        //value
        number ++;
        number +=2;
    }//end doesNothing

}//end class

The parameter number is changed inside the method doesNothing but it has no effect on the value of num in the main method. 

 

/*Array6
*Programmed by: Mr. J. Augustine
*This program demonstrates that arrays are passed by reference, not values, and
*therefore, can be manipulated in a receiving method.*/

public class Array6{

    public static void main (String[ ]args){
        //The main method, the program starts here.
        int numList [ ] = {1,2,3,4,5};
        //Create and initialize an integer array of size 5
        System.out.println("The original values of the array are: ");
        //Print out the original values of the array to the screen using a for loop
        for (int i =0; i < numList.length; i++){
            System.out.println("The value of numList [" + i + "] is " + numList[i]);
        }//end for

        doesSomething(numList);
        //The array parameter is passed to the method by reference

        System.out.println("The new values of the array are: ");
        for (int i =0; i < numList.length; i++){
            //Print out the new values of the array using a for loop
            System.out.println("The value of numList [" + i + "] is " + numList[i]);
        }//end for

    }//end main

    public static void doesSomething(int number[ ]){
        //This method receives an array as a parameter and makes some
        //minor but noticeable changes to each element.
        for (int i = 0; i <number.length; i++){
            //The for loop will multiply each element of the array by 2
            number[i] *=2;
        }//end for

    }//end doesSomething
}//end class

 

Try running this program.  What do you notice about the new array values?  They are changed as an array in Java is passed by reference not value.  In other words the address in memory of the array is passed to the method, it makes changes to the original array not a copy so the changes are maintained in the main method.

Note the use of the length attribute of an array.  If numList is an array, then numList.length is the number of elements in the array.

Note as well that the array parameter in the receiving method is described simply as: (int number [ ]).  This allows any size of integer array to be used with the method.  When an array is passed as a parameter, only the array name is provided as in the statement: doesSomething(numList);



 

More Methods and Arrays

The following program is the golf scores program but this time written using input and output methods instead of having all the code in the main method.

/*The Array7 Program
*Programmed by: Mr. J. Augustine
*This program demonstrates the initialization of an array using
*keyboard entries. This program allows the user to enter their golf score
*in a 9-hole golf course, entering the scores into an array. The program
*then allows the user to enter array elements, and show the user the
*golf score that has been entered into that element.*/

import javax.swing.JOptionPane;

public class Array7{

    public static void main (String[ ]args){
        //The main program starts here. This method will call input and output
        //methods.
        int golf [ ] = new int [9]; //Declares a new array of size 9 to hold integer values.
        getScores(golf);
        showScores (golf);
        System.exit(0);
    }//end main

    public static void getScores (int scoreList [ ]){
        //This method allows the user to input golf scores into an array.
        String input; //Holds the user's input.
        for (int i=0; i<9 ; i++){
            //This for loop sets the value for an array element to an input
            //from the user.
            input = JOptionPane.showInputDialog("Please enter your score for hole #" + (i+1));
            //We add one to the input message because there is no golf hole 0.
            scoreList[i] = Integer.parseInt(input);
        }//end for
    }//end getScores method

    public static void showScores (int scoreList [ ]){
        //This method is used to display the contents of an array on the screen.
        String input;
        input = JOptionPane.showInputDialog("Enter which hole you would like to see your score for 

                                                                                                                                   or enter -1 to exit.");
        int element = Integer.parseInt(input);

        while (element != -1){
            //This while loop allows the user to see the value stored in the
            //array element that they have entered, until they wish to exit.
            JOptionPane.showMessageDialog(null, "Your score for golf hole # " + element + " is : " + 

                                                                                                                              scoreList [element-1]);
            //We must subtract one from the element in the output message because there is no golf 

           //  hole 0
            input = JOptionPane.showInputDialog("Enter which hole you would like to see your score

                                                                                                                               for or enter -1 to exit.");
            element = Integer.parseInt(input);
        }//end while
    }//end showScores method
}//end class


      

Two Dimensional Arrays

Arrays in Java can have two or more dimensions. A common use of two dimensional array is to represent tables of values consisting of information arranged in rows and columns. To identify a particular table element, we must specify two subscripts: The first (by convention) identifies the element's row, and the second (by convention) identifies the element's column. Tables or arrays that require two subscripts to identify a particular element are called two dimensional arrays. Note that an array can have more than two dimension and such arrays are called multi dimensional arrays.

The diagram below illustrates a two dimensional array, a. The array contains three rows and four columns, so it is said to be a 3-by-4 array. In general, an array with m rows and n columns is called m-by-n array.

a[0][0] a[0][1] a[0][2] a[0][3]
a[1][0] a[1][1] a[1][2] a[1][3]
a[2][0] a[2][1] a[2][2] a[2][3]

                                   

                                            Array name       Row        Column

A two dimensional array can be initialized in its declaration much like a single subscripted array. For example, a two dimensional array b[2][2] could be declared and initialized with

                                        int b[2][2] = { {1, 2} , {3, 4} };

The values are grouped by rows in braces. So, b[0][0] = 1, b[0][1] = 2, b[1][0] = 3 and b[1][1] = 4.

 

Sample Programs

The following programs illustrate the use of two dimensional arrays:

/*The TwoDimArray Program
*Programmed by: Mr. J. Augustine, April 2004
*This program prompts the user to enter single digit numbers and store them in a two dimensional array
*Then displays the content of the array on the screen*/

import javax.swing.JOptionPane;
import java.io.*;
public class TwoDimArray1 {

public static void main(String[] args) {
int array[][] = new int[3][4];//A three by four array to store inputs

//Nested for loop to get the input and store them in the two dimensional array

for(int row =0; row <3; row++){
for(int column=0; column<4; column++){
String strArray = JOptionPane.showInputDialog("Please enter row "+ (row+1)+ " and column " +(column+1)+ " value");
array[row][column]=Integer.parseInt(strArray);

//to trap invalid input
while (array[row][column]<0 || array[row][column]>9){
strArray = JOptionPane.showInputDialog("Please enter a single digit number");
array[row][column]=Integer.parseInt(strArray);
}

}//end of inner loop
}//end of outer loop



//Nested for loop to display the contents of the array on the screen
for(int row=0; row<3; row++){
for (int column =0; column<4; column++){
System.out.print(array[row][column]+"\t");
}//end of inner loop

System.out.println();//Prints a new line

}//end of outer loop

System.exit(0);

}//end of main method
}//end of class

****************************************************************************************************************************

/*The TwoDimArray2 Program
*Programmed by: Mr. J. Augustine, April 2004
*This program is a simple demonstration of the declaration, initialization,
*and screen print out of a two-dimensional integer array.*/
public class TwoDimArray2{
public static void main (String[ ]args){
int grid [ ][ ] = new int [11][11];
//This declares a new 2D array of size 11 x 11 to hold
//integer data type elements.

clearGrid(grid, 11); //Calls the method clearGrid, passing the array grid, and value 11
showGrid(grid, 11); //Calls the method showGrid, passing the array grid, and value 11
}//end main

public static void clearGrid(int square [ ][ ], int size){
//This method sets all the value of all elements of
//the array to 0.

for (int row = 0; row < size; row++){
//This for loop is used for the rows of the 2D array.
for (int column = 0; column < size ; column++){
//This for loop is used for the columns of the 2D array.
square[row][column] = 0;
}//end inner for loop
}//end outer for loop
}//end clearGrid
public static void showGrid(int square [ ][ ], int size){
//This method will print out each element of the array to the screen.
for (int row = 0; row < size; row++){
//This for loop is used for the rows of the 2D array.
for (int column = 0; column < size ; column++){
//This for loop is used for the columns of the 2D array.
System.out.print(" " + square[row][column]);
}//end inner for loop
System.out.println(); //Prints a new line.
}//end outer for loop

}//end showGrid
}//end class
 

***************************************************************************************************************************

/*The TwoDimArray3 Program
* Programmed by: Mr. J. Augustine, April 2004
* This program allows the user to input 6 subject marks for 10 students
* Then displays the marks in a table*/

import javax.swing.JOptionPane;

public class TwoDimArray3 {

public static void main(String [] args){
String marks[][] =new String[6][10];// 6 by 10 array to hold the marks
// Nested for loop to store the marks from the user
for(int subject =0; subject<6; subject++){
for (int mark=0; mark<10; mark++){
marks[subject][mark] =JOptionPane.showInputDialog("Please enter subject " + (subject+1) + " marks");

}// end of inner loop
}// end of outer loop

//Loop to print the students names in a row with a tab spacing between names
for (int i=1; i<11; i++){
System.out.print("\tStudent#"+(i));
}// end of for loop

// For loop to print the marks in the table
for(int subject =0; subject<6; subject++){
System.out.println();//Prints a new line
System.out.print("Subject"+(subject +1));//Prints the subject name

for (int mark=0; mark<10; mark++){
System.out.print("\t");//To get a tab spacing between marks

System.out.print(marks[subject][mark]);

}//end of inner loop

}
System.exit(0);
}// end of main method
}// end of class

 

Hosted by www.Geocities.ws

1