Difference between revisions of "Processing Arrays (using for loops)"

From CompSciWiki
Jump to: navigation, search
(I added an "an". I also we worded the sentence because the sentance before had 2 unrealated thoughts in it.)
m (Updated codes.)
 
(9 intermediate revisions by 4 users not shown)
Line 1: Line 1:
{{1010Topic|Introduction=This chapter describes some of the various uses of arrays|
+
{{Template:1010Topic
Overview=
+
|Chapter_TOC=[[Arrays]]
*[[#length attribute|length attribute]]
+
|Previous=[[Out of Bounds and One off Errors]]
*[[#print content of array|print content of array]]
+
|Next=[[Review Questions and Exercises]]
*[[#copying arrays|copying arrays]]
+
|Body=
*[[#comparing arrays|comparing arrays]]
+
==Introduction==
*[[#summing values|summing values]]
+
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.
*[[#finding average of values|finding average of values]]
+
 
*[[#find highest and lowest values|find highest and lowest values]]|Chapter_TOC=[[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==
 
==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.
 
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.
Line 14: Line 17:
 
The format of how to use the length attribute would be:
 
The format of how to use the length attribute would be:
  
<pre>
+
{{CodeBlock
a = array.length;
+
|Code=
</pre>
+
int[] numberArray = new int[100];
 +
int numberArrayLength;
  
In this statement, '''"a"''' is a variable equal to the length of the array, '''"array"''' is the variable name of an array, and '''".length"''' is a statement returning the length of the array.<br><br>
+
numberArrayLength = numberArray.length;
 +
}}
  
 
'''Example''': set the values in an array equal to a loop iterator.
 
'''Example''': set the values in an array equal to a loop iterator.
<pre>
+
 
 +
{{CodeBlock
 +
|Code=
 
int i;                  //loop iterator
 
int i;                  //loop iterator
 
int[] a;                //array of ints
 
int[] a;                //array of ints
Line 27: Line 34:
 
a = new int[10]          //length 10 elements
 
a = new int[10]          //length 10 elements
  
for (i = 0; i < a.length; i++)  
+
for (i = 0; i < a.length; i++) //iterate through an array
{//iterate through an array
+
{
 
     a[i] = i;  //set element i equal to the value of i
 
     a[i] = i;  //set element i equal to the value of i
 
}
 
}
</pre>
+
 
 +
}}
  
 
This example iterates through the array, '''a''', inserting the value of '''i''' into each element. <br>  
 
This example iterates through the array, '''a''', inserting the value of '''i''' into each element. <br>  
 
Note the format of the for loop:
 
Note the format of the for loop:
  
<pre>
+
{{CodeBlock
 +
|Code=
 
for (i = 0; i < a.length; i++)  
 
for (i = 0; i < a.length; i++)  
</pre>
+
{
 +
    //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.
 
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==
 
  
 +
==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:
 
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:
  
<pre>
+
{{CodeBlock
//A simple main method.
+
|Code=
public static void main(String []args)
+
public static void main(String []args){ //A simple main method.
{
+
 
     int[] myArray;              //create a new array
 
     int[] myArray;              //create a new array
 
     myArray = createIntArray(); //set our array to this method's return value
 
     myArray = createIntArray(); //set our array to this method's return value
Line 55: Line 66:
 
}//main()
 
}//main()
  
 
+
public int[] createIntArray(){ //Return an array filled with random ints.
 
+
//Return an array filled with random ints.
+
public int[] createIntArray()
+
{
+
 
     //For this example, we do not need to know how the  
 
     //For this example, we do not need to know how the  
 
     //array is created.  Just know that this program  
 
     //array is created.  Just know that this program  
 
     //will return an array of random ints for us.   
 
     //will return an array of random ints for us.   
}printIntArray()
+
}//createIntArray()
  
 
+
public static void printIntArray(int[] array){ //Print the contents of an int array.
 
+
//Print the contents of an int array.
+
public static void printIntArray(int[] array)
+
{
+
 
     System.out.println("Printing the contents of array:");
 
     System.out.println("Printing the contents of array:");
  
 
     for (int i=0; i<array.length; i++)
 
     for (int i=0; i<array.length; i++)
     {//Print element i
+
     {
           System.out.print(array[i]);
+
           System.out.print(array[i]);//Print element i
 
     }
 
     }
  
 
     System.out.println();
 
     System.out.println();
 
}//printIntArray()
 
}//printIntArray()
</pre>
+
}}
  
 
An array can also store character, double and floating values. So you can easily display those values by using print or println method.
 
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==
 
  
 +
==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:
 
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:
  
<pre>
+
{{CodeBlock
int array1[]={1,2,3};
+
|Code=
 +
int array1[]={1,2,3};
 
int array2[]=array1;
 
int array2[]=array1;
 +
}}
  
</pre>
 
 
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.
 
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''.
 
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''.
  
<pre>
+
{{CodeBlock
 +
|Code=
 
int []array1={2,3,6};
 
int []array1={2,3,6};
 
int array2[]=new int[3];
 
int array2[]=new int[3];
Line 102: Line 107:
 
for(int i=0;i<3;i++)
 
for(int i=0;i<3;i++)
 
{
 
{
  array2[i]=array1[i];
+
    array2[i]=array1[i];
 
}
 
}
  
</pre>
+
}}
  
 
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.
 
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.
  
<pre>
+
{{CodeBlock
 
+
|Code=
 
int array2[]=(int [])array1.clone();
 
int array2[]=(int [])array1.clone();
 
+
}}
</pre>
+
  
 
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:
 
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:
  
<pre>
+
{{CodeBlock
 
+
|Code=
 
arraycopy(sourceArray, src_position, targetArray, trg_position, length);
 
arraycopy(sourceArray, src_position, targetArray, trg_position, length);
 
+
}}
</pre>
+
  
 
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:
 
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:
  
<pre>
+
{{CodeBlock
 
+
|Code=
 
int []array1={2,3,6};
 
int []array1={2,3,6};
 
int array2[]=new int[array1.length];
 
int array2[]=new int[array1.length];
 
System.arraycopy(array1,0,array2,0,array2.length);
 
System.arraycopy(array1,0,array2,0,array2.length);
 
+
}}
</pre>
+
  
 
Note: ''arraycopy'' method does not allocate memory space for the target array. So you have to create a target array before copying.
 
Note: ''arraycopy'' method does not allocate memory space for the target array. So you have to create a target array before copying.
 +
  
 
==Comparing Arrays==
 
==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.
 
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.
  
<pre>
+
{{CodeBlock
 +
|Code=
 
int []array1={1,2,3};
 
int []array1={1,2,3};
 
int []array2={1,2,3};
 
int []array2={1,2,3};
  
if(array1==array2)   //This is a mistake.
+
if(array1==array2)//This is a mistake
 
{
 
{
  System.out.println(“Same Array”);
+
    System.out.println(“Same Array”);
}  
+
}
 
else
 
else
 +
{
 +
    System.out.println(“Different Array”);
 +
}
  
  System.out.println(“Different Array”);
+
}}
 
+
</pre>
+
  
 
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.
 
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.
Line 156: Line 161:
 
In order to compare two arrays you have to compare each and every elements of array. Here is a simple example:
 
In order to compare two arrays you have to compare each and every elements of array. Here is a simple example:
  
<pre>
+
{{CodeBlock
 
+
|Code=
 
int []array1={1,2,3};
 
int []array1={1,2,3};
 
int []array2={1,2,3};
 
int []array2={1,2,3};
Line 166: Line 171:
 
if(array1.length!=array2.length)
 
if(array1.length!=array2.length)
 
{
 
{
      equal=false;
+
    equal=false;
 
}  
 
}  
  
 
for(int i=0;i<array1.length;i++)
 
for(int i=0;i<array1.length;i++)
 
{   
 
{   
  //checking for the same data
+
    if(array1[i]!=array2[i]) //checking for the same data
  if(array1[i]!=array2[i])
+
    {
  equal=false;
+
          equal=false;
 +
    }
 
}
 
}
  
If(equal)
+
if(equal)
 
{
 
{
  System.out.println(“The arrays are equals”);
+
    System.out.println(“The arrays are equals”);
 
}
 
}
 
 
else
 
else
 
{
 
{
  System.out.println(“The arrays are not equals”);
+
    System.out.println(“The arrays are not equals”);
 
+
 
}
 
}
  
</pre>
+
}}
  
  
 
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.
 
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.
 
First, this code determines the length of the array then it starts to check for the each element of an array.
 +
  
 
==Summing Values==
 
==Summing Values==
Line 202: Line 207:
 
Here is an example of code that would sum the values of an array:
 
Here is an example of code that would sum the values of an array:
  
<pre>
+
{{CodeBlock
 +
|Code=
 
int sum = 0;
 
int sum = 0;
 
int array[] = new int[100];
 
int array[] = new int[100];
Line 209: Line 215:
  
 
//sum the values
 
//sum the values
for(int i=0; i<array.length; i++) {
+
for(int i=0; i<array.length; i++)
  sum += array[i];
+
{
 +
    sum += array[i];
 
}
 
}
</pre>
+
 
 +
}}
  
 
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:
 
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:
  
<pre>
+
{{CodeBlock
int array[] = new int[100];
+
|Code=
 +
int[] array = new int[100];
  
 
for(int i=0; i<array.length; i++)
 
for(int i=0; i<array.length; i++)
  array[i] = 0;
+
{
</pre>
+
    array[i] = 0;
 +
}
 +
 
 +
}}
  
 
This loop can be inserted into your code to ensure there will be no unexpected values in the summation.
 
This loop can be inserted into your code to ensure there will be no unexpected values in the summation.
 +
  
 
==Finding Average of Values==
 
==Finding Average of Values==
Line 232: Line 245:
  
 
The following code calculates the average:
 
The following code calculates the average:
<pre>
+
{{CodeBlock
 +
|Code=
 
double average;
 
double average;
 
int sum = 0;
 
int sum = 0;
Line 240: Line 254:
  
 
//take the sum
 
//take the sum
for(int i=0; i<array.length; i++) {
+
for(int i=0; i<array.length; i++)
  sum += array[i];
+
{
 +
    sum += array[i];
 
}
 
}
  
 
//calculate the average
 
//calculate the average
 
average = sum/array.length;
 
average = sum/array.length;
</pre>
+
}}
 +
 
  
 
==Find Highest and Lowest Values==
 
==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 implment this is:
+
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
 
*The array
 
*A for loop
 
*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)
 
*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.
+
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
  
Here is how the code can look:
+
This may sound confusing so here is an example so you can see how it works.
<pre>
+
{{CodeBlock
 +
|Code=
 
int highest = INTEGER.MIN_VALUE;  //set to the lowest possible value so everything is larger
 
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 lowest = INTEGER.MAX_VALUE;    //set to the highest possible value so everything is smaller
 
int array[] = new int[100];
 
int array[] = new int[100];
  
//have values entered into the array
+
//insert values entered into the array
  
 
//go through the array
 
//go through the array
for(int i=0; i<array.length; i++) {
+
for(int i=0; i<array.length; i++)
  if(array[i] < lowest)
+
{
      lowest = array[i];
+
    if(array[i] < lowest)
  if(array[i] > highest)
+
    {
      highest = array[i];
+
          lowest = array[i];
 +
    }
 +
    if(array[i] > highest)
 +
    {
 +
          highest = array[i];
 +
    }
 
}
 
}
</pre>
+
 
 +
}}
  
 
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).  
 
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:
 
This is a sample of code that would store the positions as well as the values:
<pre>
+
{{CodeBlock
 +
|Code=
 
int highPos;
 
int highPos;
 
int lowPos;
 
int lowPos;
Line 285: Line 313:
  
 
//go through the array
 
//go through the array
for(int i=0; i<array.length; i++) {
+
for(int i=0; i<array.length; i++)
  if(array[i] < lowest) {
+
{
      lowest = array[i];
+
    if(array[i] < lowest)
      lowPos = i;
+
    {
  }
+
          lowest = array[i];
  if(array[i] > highest) {
+
          lowPos = i;
      highest = array[i];
+
    }
      highPos = i;
+
    if(array[i] > highest)
  }
+
    {
 +
          highest = array[i];
 +
          highPos = i;
 +
    }
 
}
 
}
</pre>
+
 
 +
}}
 +
 
 +
 
 +
==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]].
 +
 
 +
}}

Latest revision as of 17:56, 7 December 2011

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