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

From CompSciWiki
Jump to: navigation, search
(Removed remaining body tag and removed remaining overview tag)
(Changed introduction formatting, added summary section, added previous and next page, implemented code block template)
Line 1: Line 1:
{{1010Topic
+
{{Template:1010Topic
 +
|Chapter_TOC=[[Arrays]]
 +
|Previous=[[Out of Bounds and One off Errors]]
 +
|Next=[[Review Questions and Exercises]]
 
|Body=
 
|Body=
|Introduction=This section will cover all basic functions that can be applied to arrays.|Chapter_TOC=[[Arrays]]
+
==Introduction==
}}
+
This section will cover all basic functions that can be applied to arrays.
 +
 
 +
 
 
==Different types of 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.
 
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.
Line 11: Line 16:
 
The format of how to use the length attribute would be:
 
The format of how to use the length attribute would be:
  
<pre>
+
{{CodeBlock
 +
|Code=
 
int[] numberArray = new int[100];
 
int[] numberArray = new int[100];
 
int numberArrayLength;
 
int numberArrayLength;
  
 
numberArrayLength = numberArray.length;
 
numberArrayLength = numberArray.length;
</pre>
+
}}
  
 
'''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 28: Line 36:
 
     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>
+
}}
  
 
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.
Line 43: Line 52:
 
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
 +
|Code=
 
//A simple main method.
 
//A simple main method.
 
public static void main(String []args){
 
public static void main(String []args){
Line 50: Line 60:
 
     printIntArray(myArray);    //print contents of the array
 
     printIntArray(myArray);    //print contents of the array
 
}//main()
 
}//main()
 
 
  
 
//Return an array filled with random ints.
 
//Return an array filled with random ints.
Line 59: Line 67:
 
     //will return an array of random ints for us.   
 
     //will return an array of random ints for us.   
 
}//createIntArray()
 
}//createIntArray()
 
 
  
 
//Print the contents of an int array.
 
//Print the contents of an int array.
Line 73: Line 79:
 
     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.
Line 81: Line 87:
 
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
 +
|Code=
 
int  array1[]={1,2,3};
 
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 97: Line 105:
 
   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.
Line 131: Line 135:
 
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};
Line 141: Line 146:
 
   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 147: Line 152:
 
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 173: Line 178:
 
   System.out.println(“The arrays are not equals”);
 
   System.out.println(“The arrays are not equals”);
 
}
 
}
 
+
}}
</pre>
+
  
  
Line 189: Line 193:
 
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 199: Line 204:
 
   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
 +
|Code=
 
int[] array = new int[100];
 
int[] array = new int[100];
  
Line 209: Line 215:
 
   array[i] = 0;
 
   array[i] = 0;
 
}
 
}
</pre>
+
}}
  
 
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.
Line 220: Line 226:
  
 
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 234: Line 241:
 
//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
Line 248: Line 255:
  
 
This may sound confusing so here is an example so you can see how it works.
 
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
Line 264: Line 272:
 
   }
 
   }
 
}
 
}
</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 289: Line 298:
 
   }
 
   }
 
}
 
}
</pre>
+
}}
 +
 
  
 +
==Summary==
 
Now you should be able to find the:
 
Now you should be able to find the:
 
*Highest Value
 
*Highest Value
Line 297: Line 308:
 
*Length attribute of an array
 
*Length attribute of an array
 
*Calculate the average of an array
 
*Calculate the average of an array
 +
}}

Revision as of 23:59, 5 December 2011

COMP 1010 Home > Arrays


Introduction

This section will cover all 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++) 

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

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
Previous Page: Out of Bounds and One off Errors Next Page: Review Questions and Exercises