Page 336 - AP Computer Science A, 7th edition
P. 336

Example 2
/∗∗ Change each even-indexed element in array arr to 0.
∗ Precondition: arr contains integers.
∗ Postcondition: arr[0], arr[2], arr[4], ... have value 0.
∗/
public static void changeEven(int[] arr) {
for (int i = 0; i < arr.length; i += 2) arr[i] = 0;
}
Arrays as Parameters
Since arrays are treated as objects, passing an array as a parameter means passing its object reference. No copy is made of the array. Thus, the elements of the actual array can be accessed—and modified.
Example 1
Array elements accessed but not modified:
/∗∗ @return index of smallest element in array arr of integers ∗/
public static int findMin (int[] arr)
{
int min = arr[0];
int minIndex = 0;
for (int i = 1; i < arr.length; i++)
if (arr[i] < min) {
min = arr[i];
minIndex = i; }
return minIndex; }
//found a smaller element












































































   334   335   336   337   338