Set up a one dimensional table (i.e., one row) with 0 to (size - 1) elements
Upon instantiation of an array object, all elements contain default value for datatype stored in array OR values from the initializer list
Determine access or change of element, or action on entire array object, and update slots as needed (remembering assignment subgoals)
Accessing array element
Evaluate expression within [] which will be the index for element to be accessed
arrayName[index] returns value stored at that index
index must be between 0 and arrayName.length - 1, inclusive otherwise IndexOutOfBounds exception occurs
Changing value of an array element
Evaluate expression within [] which will be the index for element to be accessed
arrayName[index] will now contain the value on the RHS of assignment statement
(remember the assignment subgoals for verifying data types and evaluating expressions)
(remember rules for index values)
Whole array actions
Pass as argument - a copy of the reference to the instantiated array is passed to the method. This means that any changes made to the array elements inside the method are persistent. The one exception to this is if you assign the argument to reference a different array in memory.
Assignment - changes the reference to point to the array on the RHS of the assignment operator.
Subsection11.16.1
ExercisesExercises
1.
Q21: Put the following code in order to create a method that will find the last occurrence of a target value and return the index of where that value is located.
public static int find (int [] arr, int target) {
---
int loc = -1;
---
for (int i = 0; i < arr.length; i++) {
---
if (arr[i] == target)
---
loc = i;
---
}
---
return loc;
}
2.
Q22: Put the following code in order to create a method that will return true if a target value is found in the array and false otherwise.
public static boolean find (int [ ] arr, int target) {
---
for (int i = 0; i < arr.length; i++) {
---
if (arr[i] = target)
---
return true;
---
}
---
return false;
}
3.
Q23: Put the following code in order to create a method that will count the number of occurrences of a target value and return the count.
public static int count (int [] arr, int target) {
---
int num = 0;
---
for (int i = 0; i < arr.length; i++) {
---
if (arr[i] == target)
---
num++;
---
}
---
return num;
}