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

From CompSciWiki
Jump to: navigation, search
(Updated the introduction)
(reformatted some code added a warning about other array types)
Line 1: Line 1:
 
{{1010Topic|Introduction=This section will cover all basic functions that can be applied to arrays.|
 
{{1010Topic|Introduction=This section will cover all basic functions that can be applied to arrays.|
Overview=
+
Overview=After completing this section you should be able to:
*[[#length attribute|length attribute]]
+
*Find the length of an array
*[[#print content of array|print content of array]]
+
*Print the contents of an array
*[[#copying arrays|copying arrays]]
+
*Copy the contents of an array
*[[#comparing arrays|comparing arrays]]
+
*Compare an array
*[[#summing values|summing values]]
+
*Sum the values of an array
*[[#finding average of values|finding average of values]]
+
*Calculate the average of an array
*[[#find highest and lowest values|find highest and lowest values]]|Chapter_TOC=[[Arrays]]
+
*Find the highest and lowest values in an array|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 28: Line 31:
 
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
 
}
 
}
Line 49: Line 51:
 
<pre>
 
<pre>
 
//A simple main method.
 
//A simple main method.
public static void main(String []args)
+
public static void main(String []args){
{
+
 
     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 59: Line 60:
  
 
//Return an array filled with random ints.
 
//Return an array filled with random ints.
public int[] createIntArray()
+
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()
  
  
  
 
//Print the contents of an int array.
 
//Print the contents of an int array.
public static void printIntArray(int[] array)
+
public static void printIntArray(int[] array){
{
+
 
     System.out.println("Printing the contents of array:");
 
     System.out.println("Printing the contents of array:");
  
Line 101: Line 100:
 
int array2[]=new int[3];
 
int array2[]=new int[3];
  
for(int i=0;i<3;i++)
+
for(int i=0;i<3;i++){
{
+
 
   array2[i]=array1[i];
 
   array2[i]=array1[i];
 
}
 
}
Line 143: Line 141:
 
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>
 
</pre>
  
Line 165: Line 161:
  
 
//first check the size of array
 
//first check the size of array
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  
 
   //checking for the same data  
   if(array1[i]!=array2[i])
+
   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”);
 
 
}
 
}
  
Line 210: Line 202:
  
 
//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];
 
}
 
}
Line 218: Line 210:
  
 
<pre>
 
<pre>
int array[] = new int[100];
+
int[] array = new int[100];
  
for(int i=0; i<array.length; i++)
+
for(int i=0; i<array.length; i++){
 
   array[i] = 0;
 
   array[i] = 0;
 +
}
 
</pre>
 
</pre>
  
Line 241: Line 234:
  
 
//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];
 
}
 
}
Line 254: Line 247:
 
*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>
 
<pre>
 
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
Line 262: Line 259:
 
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)
+
   if(array[i] < lowest){
 
       lowest = array[i];
 
       lowest = array[i];
   if(array[i] > highest)
+
  }
 +
   if(array[i] > highest){
 
       highest = array[i];
 
       highest = array[i];
 +
  }
 
}
 
}
 
</pre>
 
</pre>
Line 286: Line 285:
  
 
//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) {
+
   if(array[i] < lowest){
 
       lowest = array[i];
 
       lowest = array[i];
 
       lowPos = i;
 
       lowPos = i;
 
   }
 
   }
   if(array[i] > highest) {
+
   if(array[i] > highest){
 
       highest = array[i];
 
       highest = array[i];
 
       highPos = i;
 
       highPos = i;
Line 297: Line 296:
 
}
 
}
 
</pre>
 
</pre>
 +
 +
Now you should be able to find the:
 +
*Highest Value
 +
*Lowest Value
 +
*Sum of the values in an array
 +
*Length attribute of an array
 +
*Calculate the average of an array

Revision as of 11:29, 5 December 2007

COMP 1010 Home > Arrays


Introduction

This section will cover all basic functions that can be applied to arrays.

   

{{{Body}}}

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++) 

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:

//A simple main method.
public static void main(String []args){
     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()



//Return an array filled with random ints.
public int[] createIntArray(){
     //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()



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

     for (int i=0; i<array.length; i++)
     {//Print element i
          System.out.print(array[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++){  
   //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

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

  • 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;
   }
}

Now you should be able to find the:

  • Highest Value
  • Lowest Value
  • Sum of the values in an array
  • Length attribute of an array
  • Calculate the average of an array