Processing Arrays (using for loops)

From CompSciWiki
Jump to: navigation, search

COMP 1010 Home > Arrays


Introduction

As you have seen in Entering and Using Array Elements, you can access and modify elements of an array. This section will cover all the basic functions that can be applied to arrays.


Different types of arrays

We are only using int arrays in this section for the single reason that calculations are made easier with int variables. If you are using an array of something other than int, double or other numeric type you will not be able to sum the contents of an array.


Array Length

Every array has a limit to the amount of data it can contain. 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:

 int[] numberArray = new int[100];
int numberArrayLength;

numberArrayLength = numberArray.length; 

Example: set the values in an array equal to a loop iterator.

 int i;                   //loop iterator
int[] a;                 //array of ints

a = new int[10]          //length 10 elements

for (i = 0; i < a.length; i++) //iterate through an array
{
    a[i] = i;   //set element i equal to the value of i
} 

This example iterates through the array, a, inserting the value of i into each element.
Note the format of the for loop:

 for (i = 0; i < a.length; i++) 
{
    //do something
} 

The for loop iterator begins at element 0, and ends before hitting a.length (10) - therefore iterating 0 through 9. Remember that an array's first element is 0, not 1! If we were to iterate until a.length (in other words, change the for loop to: i <= a.length), we would be out of bounds.


Print Array Contents

We can display the elements of an array by using print and println. The following program is quite simple. Its purpose is to shows how to display the elements in the array:

 public static void main(String []args){ //A simple main method.
     int[] myArray;              //create a new array
     myArray = createIntArray(); //set our array to this method's return value
     printIntArray(myArray);     //print contents of the array
}//main()

public int[] createIntArray(){ //Return an array filled with random ints.
     //For this example, we do not need to know how the 
     //array is created.  Just know that this program 
     //will return an array of random ints for us.  
}//createIntArray()

public static void printIntArray(int[] array){ //Print the contents of an int array.
     System.out.println("Printing the contents of array:");

     for (int i=0; i<array.length; i++)
     {
          System.out.print(array[i]);//Print element i
     }

     System.out.println();
}//printIntArray() 

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

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

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++)
{  
     if(array1[i]!=array2[i]) //checking for the same data 
     {
          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

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

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

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 implement 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:

  • Create the variables
  • Use a for loop to step through the contents of the array
  • At each step compare the current value you are examining to the previous highest and/or lowest variable
  • If the value you are looking at is larger than the largest value seen or lower than the lowest, replace the value with the one from the array

This may sound confusing so here is an example so you can see how it works.

 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];

//insert 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;
     }
} 


Summary

After reading this section you should be able to find the highest array value, the lowest array value, the sum of the values in an array, the length of an array and the average of the array values. In the next section you will find Review Questions and Exercises.

Previous Page: Out of Bounds and One off Errors Next Page: Review Questions and Exercises