90 likes | 215 Views
CSE 1341 - Honors Principles of Computer Science I. Spring 2008 Mark Fontenot mfonten@engr.smu.edu. Note Set 9. Note Set 9 Overview. Arrays Arrays and Methods Some Array Examples Multi Dimensional Arrays. Arrays and Methods. public static void main (…) {
E N D
CSE 1341 - HonorsPrinciples of Computer Science I Spring 2008 Mark Fontenot mfonten@engr.smu.edu Note Set 9
Note Set 9 Overview • Arrays • Arrays and Methods • Some Array Examples • Multi Dimensional Arrays
Arrays and Methods public static void main (…) { int[] myArr = {1, 2, 3, 4, 5}; System.out.println(sumElements(myArr)); } public static intsumElements(int[] arr) { int sum = 0; for(int x : arr ) sum += x; return sum; } If we modified arr, would the changes be reflected in myArr also? Passing an array to a method
Return an array from a method public static void main (…) { int[] myArr = createArray(10, 50); for (int x : myArr) System.out.println(x); } //Creates array filled with ints between //the two args, assuming that a < b public static intcreateArray(int a, int b) { int[] arr = new int [b – a + 1]; for (inti = a; i <= b; i++) arr[i – a] = i; } You can return an array reference from a method
Write Some Code Write a static method that accepts an integer array and returns an array holding any integer between 1 and 20 that is not stored in the parameter array.
Standard Deviation Write a method that will accept an array of integers and calculate the standard deviation of the elements of that array using the formula:
Two Dimensional Arrays Similar to a table of values with rows and columns Think of it as an array of 1-D arrays – each row is an array
Declaring a 2 D array Number of Rows int[][] x = new int [10][20]; for (inti = 0; i < x.length; i++) { for (int j = 0; j < x[i].length; j++) x[i][j] = 10; Number of columns in that row int[][] x = new int [2]; x[0] = new int[10]; //??? x[1] = new int[20]; //???
Printing elements from array public static void main (String [] args) { int[][] array1 = {{1, 2, 3}, {4, 5, 6}}; int[][] array2 = {{1, 2}, {3}, {4, 5, 6}}; outputArray (array1); outputArray (array2); } public static void outputArray(int[][]a) { for (int row = 0; row < a.lenght; row++) { for (intcol = 0; col< a[row].length; col++) System.out.printf(“%d “, a[row][col]); System.out.println(); } }