Difference between revisions of "Arrays Solutions"
(Added link back to array chapter page) |
|||
Line 7: | Line 7: | ||
===Question 2=== | ===Question 2=== | ||
− | This is called | + | This is called a one off error |
===Question 3=== | ===Question 3=== | ||
− | The second statement makes a copy of the address that is stored array1.Now array2 gets the address. | + | The second statement makes a copy of the address that is stored in array1. Now array2 gets the address. |
Line 79: | Line 79: | ||
} | } | ||
− | //displaying array | + | //displaying array elements |
for(i=0;i<10;i++) | for(i=0;i<10;i++) | ||
{ | { |
Revision as of 17:42, 5 December 2007
IntroductionThese are the solutions for the review questions for arrays. |
||
Contents
|
OverviewIf you did not answer any of these questions successfully make sure to go back and re-read the material. If you have trouble understanding the material talk to your prof or a TA |
Template loop detected: Template loop detected:
Review Questions
Question 1
This is called an out of bounds error
Question 2
This is called a one off error
Question 3
The second statement makes a copy of the address that is stored in array1. Now array2 gets the address.
Question 4
No. Here the == operator compares the memory address of the reference variable not the contents of the objects referenced by the variable.
Question 5
No. The array element array[10] is changed to "Hello", but the contents of i are unchanged.
Question 6
The string "Gello" is printed.
Exercises
Exercise 1
int product = 1; int array[] = new int[10]; //have values entered into the array //calculate the product for(int i=0; i<array.length; i++) { product *= array[i]; }
Exercise 2
int lowPos; 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; } }
Exercise 3
import java.io.*; public class CreateArray { public static void main(String []args) { //create an array int[] numbers = new int[10]; //populating array for(int i=0;i<10;i++) { numbers[i]=10+i; } //displaying array elements for(i=0;i<10;i++) { System.out.println(numbers[i]); } } }
Exercise 4
public class ArrayCopy { public static void main(String []args) { int array1[]={1,2,3,5} int array2[]=new int[4]; //This loop copys contents from array1 to array2 for(int i=0;i<array1.length();i++) { array2[i]=array1[i]; } } }
Exercise 5
public static void sortArray (int[] array) { int j = 0, k = 0, temp = 0; for (j = 0; j < array.length; j++) { for (k = 0; k < array.length - 1; k++) { if (array[k] > array[k + 1]) { temp = array[k]; array[k] = array[k + 1]; array[k + 1] = temp; } } } }
Exercise 6
void printArray (Object[] array) { int j = 0; for (j = 0; j < array.length; j++) { System.out.println(array[j].toString); } }
Template loop detected: Template loop detected: Template loop detected: