Presentation is loading. Please wait.

Presentation is loading. Please wait.

Spring 2008 Mark Fontenot CSE 1341 - Honors Principles of Computer Science I Note Set 10.

Similar presentations


Presentation on theme: "Spring 2008 Mark Fontenot CSE 1341 - Honors Principles of Computer Science I Note Set 10."— Presentation transcript:

1 Spring 2008 Mark Fontenot mfonten@engr.smu.edu CSE 1341 - Honors Principles of Computer Science I Note Set 10

2 Note Set 10 Overview Arrays Array Examples Variable-length argument lists

3 Example 1 Declare an int array of length 20 and initialize each element to the square of its subscript location. int[] arr = new int [20]; for (int i = 0; i < arr.length; i++) arr[i] = i * i;

4 Shuffle/Randomize the elements of an array Randomize the elements of the array arr from the previous example Random r = new Random(); for (int i = 0; i < arr.length; i++){ int j = r.nextInt (arr.length); //swap element i with element j int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }

5 Rolling Dice Use an array and random number generator to count the outcomes of rolling a pair of dice 10,000 times. Print the frequencies. Random r = new Random(); int[] frequency = new int[13]; for (int i = 0; i < 10000; i++) { frequency[ r.nextInt(11) + 2 ] ++; System.out.println(“%s%10s\n”, “Total”, “Frequency”); for (int i = 2; i < frequency.length; i++) System.out.printf(“%4d%10d\n”, i, frequency[i]);

6 Variable Length Argument Lists Ever notice that you can send 1, 2, 3, or more arguments to printf? It is possible to implement a method that takes a variable number of arguments public static double average(double... numbers) { double total = 0.0; for (double d : numbers) total += d; return total/numbers.length; } use the ellipsis to indicate variable length argument numbers acts like an array and can be manipulated as such

7 Rules of Variable Length Argument Lists parameter with ellipsis must be at the end of the parameter list can only be one ellipsis in a parameter list public static void foo(int... vals, int x, int y);//Don’t you dare! public static void bar(int... vals, int… otherVals);//NO NO! This is sometimes called a vararg for variable-length argument list public static double average(double... numbers)

8 Array Issues Arrays are statically sized once they are declared, they cannot change size you can allocate a new, larger array and copy the contents of the old array over. can be computationally expensive especially for large array or if this function is performed often. If you attempt to access past the end of an array, you’ll get a ArrayOutOfBounds remember that x[i] is a reference to a memory location so if you access an invalid subscript i the you would be trying to access memory you do not have access to OR the reference is NULL and thus can’t be accessed.


Download ppt "Spring 2008 Mark Fontenot CSE 1341 - Honors Principles of Computer Science I Note Set 10."

Similar presentations


Ads by Google