CS151 lecture notes, Fall 1999 Week 10, Wednesday Passing arrays as parameters ---------------------------- Good news. Everything is the same as passing objects as parameters. 1) A reference gets passed 2) Caller and callee have two references to the same object (aliasing) 3) Callee can modify the contents of the array. Example: public static int sum (int[] a) { int i = 0; int total = 0; while (i < a.length) { total += a[i]; i++; } return total; } public static void main (String[] args) { int[] array = new int[10]; // put values into the array System.out.println ("sum = " + sum(array)); } Hey, look! The parameter to main makes sense, finally! Traversals ---------- Different kinds of traversals: ACCUMULATION public static int sum (int[] a) { int i = 0; int total = 0; while (i < a.length) { total += a[i]; i++; } return total; } COUNTING public static int frequency (int[] a, int p) { int i = 0; int count = 0; while (i < a.length) { if (a[i] == p) count++; i++; } return count; } EUREKA: finding the first thing that satisfies a criterion public static int find (int[] a, int p) { int i = 0; while (i < a.length) { if (a[i] == p) return i; i++; } return -1; } EXTREME VALUE FINDING public static int max (int[] a) { int max = a[0]; int i = 1; while (i < a.length) { if (a[i] > max) max = a[i]; i++; } return max; } Think of max as "the biggest thing we've seen so far" How to generalize these things? ------------------------------ Specify a range of indices over which to sum/count/search. for loops --------- Exactly the same as a while loop, different syntax INITIALIZER while (CONDITION) { BODY INCREMENTOR } Problem: the loop-controlling statements are scattered all over. How many times do you forget the INCREMENTOR? Try this... for (INITIALIZER; CONDITION; INCREMENTOR) { BODY }