Code to Manipulate Values Inside Arrays

Code to Find the Maximum Value in an Array

int[] a = new int[N];
//N can be anything and you can initialize 
//this array with any values you want.
double max = a[0];
for(int i = 1; i < a.length; i++) {
	if(a[i] > max) max = a[i];
}

This code should be fairly self explanatory, but basically the for loop (which will iterate for as long as the number of elements in the array) has a conditional statement which tests to see if a place holding variable (max) is larger or equal to the current element in the array. If it is not, than max is set equal to the current element in the array until all of the elements have been tested. Max will hold the largest value in the array.



Code to Find the Average of the Elements in an Array

int[] a = new int[N];
//N can be anything and you can initialize 
//this array with any values you want.
double sum = 0.0;
for(int i = 0; i < N; i++) {
    sum += a[i];
}
double average = sum / N;

This snippet is again fairly simple, but can be extremely useful in many situations including scientific and mathematic computing. The sum of all of the elements is stored in the "sum" variable and in each iteration through the for loop, an element is added to the running total. Another variable, "average" stores the average of the running sum by dividing the sum variable from the number of elements in the array represented by "N". After the for loop finishes you can use the average of your array which is stored in "average".



Code to Copy all of the Elements in an Array to another Array

double[] a = new double[N];
//N can be anything and you can initialize 
//this array with any values you want.

double[] b = new double[N];
for(int i = 0; i < N; i++) {
    b[i] = a[i];
}

This code snippet is self explanatory and does not need much explanation. All that is done is a creation of a new array with the same number of elements the original had which is represented by "N". Then, the new array "b" is initialized with the values of the first array "a".


Code to Reverse the Elements in an Array

int[] a = new int[N];
//N can be anything and you can initialize 
//this array with any values you want.
for(int i = 0; i < N/2; i++) {
    int temp = a[i];
    a[i] = a[N-i-1];
    a[N-i-1] = temp;
} 

This snippet is a bit more difficult to understand at first glance. First of all, unlike the other three, the for loop does not iterate through the length of the entire array, but only half of "N". This is because this algorithm does not need to see the entire array to reverse the order of elements. First we set up a temporary array called "temp". This holds the current value of "a[i]". Then a[i] is set to the value of the element at a[N-i-1], which is it's opposite or reverse. Then that value is set equal to "temp" effectively reversing all of the elements in the array, while only needing to see the first half of the array.