Processing Arrays (using for loops)

From CompSciWiki
Revision as of 11:13, 27 November 2007 by Tyson (Talk | contribs)

Jump to: navigation, search

COMP 1010 Home > Back to Chapter Topics


Introduction

This chapter describes some of the various uses of arrays

   

{{{Body}}}

length attribute

(Graham)

Every array has a limit to the amount of data it can contain. To tell when you have reached this limit, arrays have an attribute called the "length" attribute. The length attribute is equal to the maximum number of elements you can contain in an array.

The format of how to use the length attribute would be:


    a = array.length;

where a is the variable which you want to set to the length of the array, array is the array to find the length of, and .length refers to getting the length attribute from the array.

Example:

int i = 0;
char[] v = new char[10]

for (i = 0; i < v.length; i++) {
    v[i] = "A";
}

This example would set every element in array v to the value "A".

print content of array

(ABU)

We can display the elements of array by using print and println. The following simple program shows how to display array elements:

//This program stores values in array and displays

public class ArrayDisplay
{
      public static void main(String []args)
     {
          int array[]=new int[5];  //declaring array of size 5;

          for(int i=0;i<5;i++)
          { 
             array[i]=i+10;     //populating array
          }     
         
          System.out.println("Here is the array elements:");
          //Displaying array elements
          for (int j=0;j<5;j++)
          {
           System.out.println(array[j]);
          }      

     }
}

The output of this program would be

Here is the array elements:
10
11
12
13
14

When going through the array, the variable index starts at 0. So, during the loop’s first iteration, the loop is examining array[0]. Here the stored value would be value of index +10.Then the index is incremented. So the index value becomes 1.This continues until values have been stored in all of the elements of the array.

An array can also store character, double and floating values. So you can easily display those values by using print or println method.

copying arrays

(ABU)

An array is an object, so there is a distinction between an array and the variables that reference it. The arrays and reference variables are two separate entities. When we wish to copy the contents of an array we need to remember this. Here is an example:

int  array1[]={1,2,3};
int array2[]=array1;

This example does not copy the array. The first statement creates and assigns its address to the array1 variable. The second statement assigns array1 to array2. This does not make a copy of the array1 to array2.It actually makes a copy of address of array1 and stores it in array2. After this statement both the array variables will reference the same array. Array2 is called a reference copy. Therefore, if you make any changes to array1 the changes will be reflected on array to and vice versa; since, only the address of the array object is copied not the contents of the array objects.

If you want to copy the array's contents, you can do this by copying the individual elements of array to another array. This can be done using for loops. In the following example array2 gets the contents of array1.

int []array1={2,3,6};
int array2[]=new int[3];

for(int i=0;i<3;i++)
{
  array2[i]=array1[i];
}

As we know an array is treated as an object in java. You can also use the clone method to copy array. The following statement uses the clone method to copy array1 to array2.


int array2[]=(int [])array1.clone();

Another approach is to use the arraycopy() method in the java.lang.System class to copy arrays instead of using a loop. Here is the syntex:


arraycopy(sourceArray, src_position, targetArray, trg_position, length);

The parameter src_position and trg_position indicates the starting position in the sourceArray and targetArray respectively. The length indicates the number of elements copied from source to targer array. Now you can rewrite the loop using the following statement:


int []array1={2,3,6};
int array2[]=new int[array1.length];
System.arraycopy(array1,0,array2,0,array2.length);

Note: arraycopy method does not allocate memory space for the target array. So you have to create a target array before copying.

comparing arrays

(ABU)

We can not compare arrays by using ==.We can use == operator to compare two references variables including those that reference array. The operator compares the memory address that the variable contains not the content of object referenced by variables. In this following example we compare two arrays.

int []array1={1,2,3};
int []array2={1,2,3};

if(array1==array2)   //This is a mistake.
{
  System.out.println(“Same Array”);
} 
else

  System.out.println(“Different Array”);

This example is wrong because two array variables refer to two different objects of memory. Therefore, the result of the boolean expression of array1=array2 is false and it will display that arrays are not the same.

In order to compare two arrays you have to compare each and every elements of array. Here is a simple example:


int []array1={1,2,3};
int []array2={1,2,3};

boolean equal=true;

//first check the size of array
if(array1.length!=array2.length)
{
      equal=false;
} 

for(int i=0;i<array1.length;i++)
{  
   //checking for the same data 
   if(array1[i]!=array2[i])  
   equal=false;
}

If(equal)
{
   System.out.println(“The arrays are equals”);
}

else
{
   System.out.println(“The arrays are not equals”);

}


This example determines whether array1 and array2 contain the same data or not. A boolean flag variable equal which is initialized to true, is used to signal wether the arrays are equal. First, this code determines the length of the array then it starts to check for the each element of an array.

Summing Values

(Andrew)

You may find, when using int or double arrays, that you will need to take the sum of the contents. You need the following to perform this operation:

  • The array
  • A variable to count the sum (can be int or double, depending on what is needed) initialized to zero
  • A for loop

Wondering how to do it? Once you have the values initialized (you've created the variables and placed some values into the array) you use the for loop to step through all the positions of the array, adding the value stored in that location to the summation counter. Once the loop has concluded, you will have the sum of the contents.

Here is an example of code that would sum the values of an array:

int sum = 0;
int array[] = new int[100];

//have values entered into the array

//sum the values
for(int i=0; i<array.length; i++) {
   sum += array[i];
}

A word of warning: not all Java compilers initialize the values to zero. When first creating the array, it would be a good idea to set the values to zero. You can do this with a simple for loop:

int array[] = new int[100];

for(int i=0; i<array.length; i++)
   array[i] = 0;

This loop can be inserted into your code to ensure there will be no unexpected values in the summation.

Finding Average of Values

(Andrew)

A task you may one day need to perform is to calculate the average of all values within an int or double array. This process is very similar to the code for summing all the values within the array. In fact, it's more of an extension upon a summation as you still need to find the sum of all the values. You can change a summation method to calculate the average by adding only two lines. The two new lines you will need to add are:

  • Declare a variable to hold the average value
  • Calculate the average and store it in the new variable

You can declare the new variable as either an int or a double, depending on what level of precision you want.

The following code calculates the average:

double average;
int sum = 0;
int array = new int[100];

//have values entered into the array

//take the sum
for(int i=0; i<array.length; i++) {
   sum += array[i];
}

//calculate the average
average = sum/array.length;

Find Highest and Lowest Values

(Andrew)

Oftentimes you'll find the need to search for a highest and/or lowest value in a set. This is a simple job to accomplish. All you will need to implment this is:

  • The array
  • A for loop
  • A variable for each value you want to store (one if you want just the highest or lowest, two if you want both)

What you need to do is (after all the variables have been created) use the for loop to step through the contents of the array. At each step, you compare the current value you are examining in the array to what has been stored in the current highest and/or lowest variable. If the value you are looking at is larger than the largest value seen or smaller than the smallest, replace the value with the one from the array.

Here is how the code can look:

int highest = INTEGER.MIN_VALUE;   //set to the lowest possible value so everything is larger
int lowest = INTEGER.MAX_VALUE;    //set to the highest possible value so everything is smaller
int array[] = new int[100];

//have values entered into the array

//go through the array
for(int i=0; i<array.length; i++) {
   if(array[i] < lowest)
      lowest = array[i];
   if(array[i] > highest)
      highest = array[i];
}

If you want, you can identify the position(s) in the array in which the highest and/or lowest value is found. What you need for this another one or two int variables (one to store the highest or lowest, two if you want them both).

This is a sample of code that would store the positions as well as the values:

int highPos;
int lowPos;
int highest = INTEGER.MIN_VALUE;   //set to the lowest possible value so everything is larger
int lowest = INTEGER.MAX_VALUE;    //set to the highest possible value so everything is smaller
int array[] = new int[100];

//have values entered into the array

//go through the array
for(int i=0; i<array.length; i++) {
   if(array[i] < lowest) {
      lowest = array[i];
      lowPos = i;
   }
   if(array[i] > highest) {
      highest = array[i];
      highPos = i;
   }
}