Presentation is loading. Please wait.

Presentation is loading. Please wait.

Arrays CS 180 15 Feb 2008. Announcements Exam 1 Grades on Blackboard Project 2 scores: end of Class Project 4, due date:20 th Feb –Snakes & Ladders Game.

Similar presentations


Presentation on theme: "Arrays CS 180 15 Feb 2008. Announcements Exam 1 Grades on Blackboard Project 2 scores: end of Class Project 4, due date:20 th Feb –Snakes & Ladders Game."— Presentation transcript:

1 Arrays CS 180 15 Feb 2008

2 Announcements Exam 1 Grades on Blackboard Project 2 scores: end of Class Project 4, due date:20 th Feb –Snakes & Ladders Game Review of Q5,Q8,Q11 & Programming Questions

3 Arrays: What they mean? An array is an object used to store a (possibly large) collection of data. All the data stored in the array must be of the same type. It enables you to use a single name to represent a collection of items & refer to an item by specifying the item number

4 Types of Arrays One-Dimensional Arrays –int students[ 5] Multi-Dimensional arrays –Simplest form is a 2-D Array int students[3 ][ 5] –Example of 3-D Array int students[ 5][7 ][ 3]

5 Creating an Array Declare an array – 2 forms –type arrayname[ ]; Ex: int number[ ]; –type [ ] arrayname; Ex: int [ ] number; Create memory location –arrayname= new type[size]; –Ex: number= new int[2]; –Here we have created an array of type integer with 2 elements and named it as number Put values –arrayname[index]=value; –Ex: number[0]=35; –Ex: number[1]=40;

6 Diagram: Creation of Array Statement int number[ ]; number=new int[2]; This is an array of length 2 “number” is a reference that points to the first memory address Result number points nowhere number number [0] number [1] Memory locations

7 Index / Subscript of Array –int number [i] –Here “i” is an integer used to refer to an element of the array number. It is called the Index Ex: number[0] : indicates the first element of number Ex: number[1] : indicates the second element of number Length: Instance Variable length is a public instance variable The length variable stores the number of elements the array can hold. Using Array_Name.length typically produces clearer code than using an integer literal.

8 Array Terminology

9 Array index out of bounds It is a runtime error which is caused by incorrect use of array index. –Ex: int number[]=new int[2]; –number[0]=1; –number[1]=2; –number[2]=17; Error : array “number” has just 2 elements!

10 Initializing Arrays An array can be initialized at the time it is declared. example double[] reading = {3, 3, 15.8, 9.7}; –The size of the array is determined by the number of values in the initializer list.

11 Initializing Arrays, cont. Uninitialized array elements are set to the default value of the base type. However, it’s better to use either an initializer list or a for loop. int[] count = new int[100]; for (int i = 0, i < count.length, i++) { count[i] = 0; }

12 Arrays in Classes & Methods Arrays can be used as instance variables in classes. Both an indexed variable of an array and an entire array can be a argument of a method. Methods can return an indexed variable of an array or an entire array.

13 Arrays in Classes & Methods Example class cs180Class { String studentName[], firstName[]; public cs180Class() { System.out.println("enter number of students:"); int num_students=keyboard.nextInt(); firstName = new String[num_students];... studentName = setData(firstName); } String[] setData (String name[ ]) { String[] temp = new String [name.length]; for(int i=0; i < name.length; i++) { temp[i] = name[i]; } return temp; } } Array as instance variables Array as argument of a method: Call by Value Returning an Array

14 What about Main method? Recall the heading for method main : public static void main(String[] args) An array of String values can be provided in the command line. example java TestProgram Mary Lou –args[0] is set to “Mary” –args[1] is set to “Lou” System.out.println(“Hello “ + args[0] + “ “ + args[1]); prints Hello Mary Lou.

15 Use of = & == with Arrays –The assignment operator creates an alias, not a copy of the array. –The equality operator determines if two references contain the same memory address, not if two arrays contain the same values.

16 Making a Copy of an Array example int[] a = new int[50]; int[] b = new int[50];... for (int j = 0; j < a.length; j++) b[j] = a[j];

17 Determining the “Equality” of Two Arrays To determine if two arrays at different memory locations contain the same elements in the same order, define an equals method which determines if –both arrays have the same number of elements –each element in the first array is the same as the corresponding element in the second array.

18 Swapping Array elements class interchange

19 Uses of Arrays Searching an element in a list of elements Sorting –Ascending order –Descending order –Alphabetic order

20 Example: Selection Sort Selection sort begins by finding the smallest item in the array and swapping it with the item in a[0].

21 Selection Sort: class class SelectionSort

22 Multi-Dimensional Arrays 2-Dimensional Array –A row & Column structure – int [ ] [ ] world= new int[10][9] –Indexing can be done using 2 integers: i, j world [i] [j] : refers to element at row i and column j Length : 2-D array –world.length: returns the # of rows –world [i].length: returns the # of columns in row ‘i’

23 2-Dimensional Array 2-D representation double[ ][ ] Salary= new double[10][6]; Department 10, Employee 1: Salary[9][0] Salary information of 10 departments each having 6 employees

24 Initialize 2-D Arrays You can initialize by nesting of loops final int MAX_ROW = 25; final int MAX_COL = 1000; double[][] experData = new double[MAX_ROW][MAX_COL]; int i,j; for (i = 0; i < MAX_ROW; i ++) { for (j = 0; j < MAX_COL; j ++) { experData [i][j] = 0.0; } Alternate way: –double [][] scores={{5.3, 6.9, 8.8, 1.7}, {2.2, 9.4, 1.6, 7.5} }; 2 rows, 4 columns

25 Ragged Arrays Since a two-dimensional array in Java is an array of arrays, each row can have a different number of elements (columns). Arrays in which rows have different numbers of elements are called ragged arrays. Example int[][] b = new int[3][]; b[0] = new int[5]; // array of 5 elements b[1] = new int[7];// array of 7 elements b[2] = new int[4]; // array of 4 elements

26 Quiz Task : print all the system.out.println statements. public class arrayTest { public static void main(String[] args) { String[] names={"Hemant", "David", "Wini","Kaku"}; System.out.println("length of the array:" + names.length); for(int i=0;i<names.length;i++) { System.out.println(names[i]); } } }

27 Review: Exam 1 – Q5 Q5. Given the following code: double a = 1/3; double b = 1/3; double c = 1/3; double sum = a + b + c; The value of variable sum is: (a) 0.9999 (b) 0.0 (c) 0.999999999999999999 (d) 1.0 Q5. Modified Version. Given the following code: double a = 1/3; double b = 1/3; double c = 1/3; double sum = a + b + c; The value of variable sum is: –All integers: 0 –All floats 0.0 –All doubles: 0.0

28 Review: Exam 1 – Q8 What is the output of the following program fragment? String s1 = "How are you?"; String s2 = "Who are you?"; int compareVal = (s1.substring(3)).compareTo(s2.substring(3)) > 0? 1:0; switch (compareVal) { case 1: System.out.println(s1);break; case 0: System.out.println(s2); } (a) w are you? (b) How are you? Who are you? (c) Who are you? (d) How are you? Solution: s1.substring(3)--> are you? s2.substring(3)--> are you? s1.substring(3)).compareTo(s2.substring(3)-->0 Who are you? beginning index till the end of string

29 Review: Exam 1 – Q11 Which of the following are true regarding String comparison (assume s1 and s2 have been declared as String)? I. The operator "==" and the method equals always return the same result II. The compareTo method should be used to compare two strings instead of the operators ">" and "<" III. s1.compareTo(s2) returns a negative number if s1 comes after s2 lexicographically (a) I and II only (b) I, II and III (c) II only (d) II and III only

30 Review: Exam 1 – Program 1 (20 points) Write a program that prompts for a number n which indicates the number of columns and uses the number to display the following pattern (depicting n = 6 where the maximum number of X is n. X XX XXX XXXX XXXXX XXXXXX XXXXX XXXX XXX XX X

31 Review: Exam 1 – Program 2 Write a program that converts a user-defined integer n to base k where k is another user defined integer. Your program should first prompt for the integer n which will be converted, then prompt for the base value k. Your program should also write the result as a string in the following format: n = result base k

32 Review: Exam 1 – Program 3 Nicomachus’s Theorem states that the nth cubic number n3 is a sum of n consecutive odd umbers. For example: 13 = 1 23 = 3 + 5 33 = 7 + 9 + 11 43 = 13 + 15 + 17 + 19 The first term in each sequence is n(n 1) + 1. Write code for: private void initialize() public int byMultiply() public int byAdd()


Download ppt "Arrays CS 180 15 Feb 2008. Announcements Exam 1 Grades on Blackboard Project 2 scores: end of Class Project 4, due date:20 th Feb –Snakes & Ladders Game."

Similar presentations


Ads by Google