Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 7 Arrays.

Similar presentations


Presentation on theme: "Chapter 7 Arrays."— Presentation transcript:

1 Chapter 7 Arrays

2 Objectives To describe why an array is necessary in programming.
To learn the steps involved in using arrays: declaring array reference variables and creating arrays. To initialize the values in an array. To simplify programming using JDK 1.5 enhanced for loop. To copy contents from one array to another. To develop and invoke methods with array arguments and ruturn type. To sort an array using the selection sort algorithm. To search elements using the linear or binary search algorithm. To declare and create multidimensional arrays.

3 Introduction We usually store a large number of values during execution of a program. Example: read 100 numbers, compute average and find out how many numbers are above the average. The numbers must all be stored in variables in order to accomplish this task. You need to declare 100 variables and repeatedly write almost identical code 100 times. This approach is not practical and not efficient. Therefore, an organized approach is required, using a data structure called ARRAY, that stores a fixed-size sequential collection of elements of the same type.

4 Introducing Arrays Array is a data structure that represents a collection of the same types of data.

5 Declaring Array Variables
datatype[] arrayRefVar; Example: double[] myList; datatype arrayRefVar[]; // This style is //allowed, but not preferred double myList[];

6 Creating Arrays Unlike primitive data type declarations, array declarations does not allocate any space in memory for the array. Only a storage location for the reference to an array is created. If a variable does not reference to an array, the value of the variable is null. After an array is declared, you can create an array by using the new operator as follows: arrayRefVar = new datatype[arraySize]; Example: myList = new double[10]; myList[0] references the first element in the array. myList[9] references the last element in the array.

7 Declaring and Creating in One Step
datatype[] arrayRefVar = new datatype[arraySize]; double[] myList = new double[10]; datatype arrayRefVar[] = new datatype[arraySize]; double myList[] = new double[10];

8 The Length of an Array For example,
Once an array is created, its size is fixed. It cannot be changed. You can find its size using arrayRefVar.length For example, myList.length returns 10

9 Default Values When an array is created, its elements are assigned the default value of 0 for the numeric primitive data types, '\u0000' for char types, and false for boolean types.

10 Indexed Variables The array elements are accessed through the index. The array indices are 0-based, i.e., it starts from 0 to arrayRefVar.length-1. In the previous example, myList holds ten double values and the indices are from 0 to 9. Each element in the array is represented using the following syntax, known as an indexed variable: arrayRefVar[index];

11 Using Indexed Variables
After an array is created, an indexed variable can be used in the same way as a regular variable. For example, the following code adds the value in myList[0] and myList[1] to myList[2]. myList[2] = myList[0] + myList[1];

12 Array Initializers This shorthand syntax must be in one statement.
Declaring, creating, initializing in one step: double[] myList = {1.9, 2.9, 3.4, 3.5}; This shorthand syntax must be in one statement.

13 Declaring, creating, initializing Using the Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5}; This shorthand notation is equivalent to the following statements: double[] myList = new double[4]; myList[0] = 1.9; myList[1] = 2.9; myList[2] = 3.4; myList[3] = 3.5;

14 CAUTION Using the shorthand notation, you have to declare, create, and initialize the array all in one statement. Splitting it would cause a syntax error. For example, the following is wrong: double[] myList; myList = {1.9, 2.9, 3.4, 3.5};

15 Trace Program with Arrays
animation Trace Program with Arrays Declare array variable values, create an array, and assign its reference to values public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = values[i] + values[i-1]; } values[0] = values[1] + values[4];

16 Trace Program with Arrays
animation Trace Program with Arrays i becomes 1 public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = values[i] + values[i-1]; } values[0] = values[1] + values[4];

17 Trace Program with Arrays
animation Trace Program with Arrays i (=1) is less than 5 public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = values[i] + values[i-1]; } values[0] = values[1] + values[4];

18 Trace Program with Arrays
animation Trace Program with Arrays After this line is executed, value[1] is 1 public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4];

19 Trace Program with Arrays
animation Trace Program with Arrays After i++, i becomes 2 public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = values[i] + values[i-1]; } values[0] = values[1] + values[4];

20 Trace Program with Arrays
animation Trace Program with Arrays i (= 2) is less than 5 public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = values[i] + values[i-1]; } values[0] = values[1] + values[4];

21 Trace Program with Arrays
animation Trace Program with Arrays After this line is executed, values[2] is 3 (2 + 1) public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4];

22 Trace Program with Arrays
animation Trace Program with Arrays After this, i becomes 3. public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4];

23 Trace Program with Arrays
animation Trace Program with Arrays i (=3) is still less than 5. public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4];

24 Trace Program with Arrays
animation Trace Program with Arrays After this line, values[3] becomes 6 (3 + 3) public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4];

25 Trace Program with Arrays
animation Trace Program with Arrays After this, i becomes 4 public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4];

26 Trace Program with Arrays
animation Trace Program with Arrays i (=4) is still less than 5 public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4];

27 Trace Program with Arrays
animation Trace Program with Arrays After this, values[4] becomes 10 (4 + 6) public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4];

28 Trace Program with Arrays
animation Trace Program with Arrays After i++, i becomes 5 public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4];

29 Trace Program with Arrays
animation Trace Program with Arrays i ( =5) < 5 is false. Exit the loop public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4];

30 Trace Program with Arrays
animation Trace Program with Arrays After this line, values[0] is 11 (1 + 10) public class Test { public static void main(String[] args) { int[] values = new int[5]; for (int i = 1; i < 5; i++) { values[i] = i + values[i-1]; } values[0] = values[1] + values[4];

31 Processing Arrays See the examples in the text page 199.
Initializing arrays Printing arrays Summing all elements Finding the largest element Finding the smallest index of the largest element

32 Initializing arrays Initializing arrays with random values.
for (int i = 0; i < myList.length; i++) { myList[i] = Math.random() * 100; }

33 Printing Arrays for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + “ “); }

34 Summing all elements double total = 0;
for (int i = 0; i < myList.length; i++) { total += myList[i]; }

35 Finding the largest element
double max = myList[0]; for (int i = 1; i < myList.length; i++) { if(myList[i] > max) max = myList[i]; }

36 Finding the smallest index of the largest element
double max = myList[0]; int index = 0; for (int i = 1; i < myList.length; i++) { if(myList[i] > max) { max = myList[i]; index = i; }

37 Program Example Program Output: public class ArrayOperations {
public static void main (String[] args) { double[] myList = new double[5]; for (int i = 0; i < myList.length; i++) { myList[i] = (int)(Math.random() * 100); } System.out.println(myList[i] + " "); double total = 0; total += myList[i]; System.out.println("Total = " +total); double max = myList[0]; for (int i = 1; i < myList.length; i++) if(myList[i] > max) max = myList[i]; System.out.println("Max = " +max); max = myList[0]; int index = 0; if(myList[i] > max) { index = i; System.out.println("Index = " +index); Program Output:

38 Enhanced for Loop JDK 1.5 Feature
JDK 1.5 introduced a new for loop that enables you to traverse the complete array sequentially without using an index variable. For example, the following code displays all elements in the array myList: for (double value: myList) System.out.println(value); In general, the syntax is for (elementType value: arrayRefVar) { // Process the value } Example: public class ArrayOperationsSimplified { public static void main (String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; You still have to use an index variable if you wish to traverse the array in a different order or change the elements in the array. Program Output:

39 Example: Testing Arrays
Objective: The program receives 6 numbers from the user, finds the largest number and counts the occurrence of the largest number entered. Suppose you entered 3, 5, 2, 5, 5, and 5, the largest number is 5 and its occurrence count is 4.

40 Example: Testing Arrays
import javax.swing.JOptionPane; public class TestArray { /** Main method */ public static void main(String[] args) { final int TOTAL_NUMBERS = 6; int[] numbers = new int[TOTAL_NUMBERS]; // Read all numbers for (int i = 0; i < numbers.length; i++) { String numString = JOptionPane.showInputDialog( "Enter a number:"); // Convert string into integer numbers[i] = Integer.parseInt(numString); } // Find the largest int max = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (max < numbers[i]) max = numbers[i]; // Find the occurrence of the largest number int count = 0; if (numbers[i] == max) count++; // Prepare the result String output = "The array is "; for (int i = 0; i < numbers.length; i++) { output += numbers[i] + " "; } output += "\nThe largest number is " + max; output += "\nThe occurrence count of the largest number " + "is " + count; // Display the result JOptionPane.showMessageDialog(null, output);

41 Program Output: Testing Arrays

42 See Arrays in JBuilder Debugger
JBuilder Optional See Arrays in JBuilder Debugger You can trace the value of array elements in the debugger. Array

43 Example: Assigning Grades
Objective: read student scores (int), get the best score, and then assign grades based on the following scheme (refer page 202): Grade is A if score is >= best–10; Grade is B if score is >= best–20; Grade is C if score is >= best–30; Grade is D if score is >= best–40; Grade is F otherwise.

44 Example: Assigning Grades
import javax.swing.JOptionPane; public class AssignGrade { /** Main method */ public static void main(String[] args) { // Get number of students String numberOfStudentsString = JOptionPane.showInputDialog( "Please enter number of students:"); // Convert string into integer int numberOfStudents = Integer.parseInt(numberOfStudentsString); int[] scores = new int[numberOfStudents]; // Array scores int best = 0; // The best score char grade; // The grade // Read scores and find the best score for (int i = 0; i < scores.length; i++) { String scoreString = JOptionPane.showInputDialog( "Please enter a score:"); scores[i] = Integer.parseInt(scoreString); if (scores[i] > best) best = scores[i]; } // Declare and initialize output string String output = ""; // Assign and display grades for (int i = 0; i < scores.length; i++) { if (scores[i] >= best - 10) grade = 'A'; else if (scores[i] >= best - 20) grade = 'B'; else if (scores[i] >= best - 30) grade = 'C'; else if (scores[i] >= best - 40) grade = 'D'; else grade = 'F'; output += "Student " + i + " score is " + scores[i] + " and grade is " + grade + "\n"; } // Display the result JOptionPane.showMessageDialog(null, output);

45 Program Output: AssignGrade

46 Exercise Write a program that displays integer numbers 1 to 10 using arrays. The output should be as follows: 1 2 3 . 10

47 Solution public class ExerciseOne {
public static void main (String[] args) { int[] myList = new int[11]; for (int i = 1; i < myList.length; i++) { myList[i]=i; System.out.println(myList[i] + " "); }

48 Exercise Write a program that sums the numbers 1 to 10 using arrays. The output should be as follows: The summation of numbers 1 to 10 is 55

49 Solution public class ExerciseTwo {
public static void main (String[] args) { int[] myList = new int[11]; int sum=0; for (int i = 1; i < myList.length; i++) { myList[i]=i; sum+=myList[i]; } System.out.println("The summation of number 1 to 10 is " +sum);

50 Exercise What is the output of the following program?
public class PrintingArray { public static void main (String[] args) { int[] myList = new int[10]; for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + " "); }

51 Exercise What is the output of the following program?
public class PrintingArray { public static void main (String[] args) { int[] myList = new int[10]; for (int i = 5; i < myList.length; i++) { System.out.println(myList[i] + " "); }

52 Exercise What is the output of the following program?
public class Arrays { public static void main (String[] args) { int x = 30; int[] numbers = new int[x]; x = 60; System.out.println("x is " +x); System.out.println("The size of numbers is " +numbers.length); }

53 Accessing Out of Bound Array Index
What is the output of the following code? public class ExerciseOne { public static void main (String[] args) { int[] myList = {1,2,3,4,5}; System.out.println(myList[0] + " "); System.out.println(myList[1] + " "); System.out.println(myList[2] + " "); System.out.println(myList[3] + " "); System.out.println(myList[4] + " "); System.out.println(myList[5] + " "); }

54 Accessing Out of Bound Array Index
What is the output of the following code? public class ExerciseOne { public static void main (String[] args) { int[] myList = {1,2,3,4,5}; System.out.println(myList[0] + " "); System.out.println(myList[1] + " "); System.out.println(myList[2] + " "); System.out.println(myList[3] + " "); System.out.println(myList[4] + " "); System.out.println(myList[5] + " "); } Output:

55 Copying Arrays Often, in a program, you need to duplicate an array or a part of an array. In such cases you could attempt to use the assignment statement (=), as follows: list1 & list2 point to separate memory locations list1 array is passed to list2 In Java, you can use assignment statements to copy primitive data type variables, but not arrays. Assigning one array variable to another array variable actually copies one reference to another and makes both variables point to the same memory location.

56 Copying Arrays Using a loop: int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new int[sourceArray.length]; for (int i = 0; i < sourceArrays.length; i++) targetArray[i] = sourceArray[i];

57 The arraycopy Utility arraycopy(sourceArray, src_pos, targetArray, tar_pos, length); Example: System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);

58 Example: Copying Arrays
public class CopyingArray { public static void main (String[] args) { int[] sourceArray = {2, 3, 1, 5, 10}; int[] targetArray = new int[sourceArray.length]; double[] sourceArray1 = {1.2, 2.3, 3.4, 4.5, 5.6}; double[] targetArray1 = new double[sourceArray.length]; char[] sourceArray2 = {'A', 'B', 'C', 'D', 'E'}; char[] targetArray2 = new char[sourceArray2.length]; System.out.println("Copy Array 1:"); for (int i = 0; i < sourceArray.length; i++){ targetArray[i] = sourceArray[i]; System.out.println(targetArray[i]); } //end for System.out.println(); System.out.println("Copy Array 2:"); for (int i = 0; i < sourceArray1.length; i++){ targetArray1[i] = sourceArray1[i]; System.out.println(targetArray1[i]); } //end for System.out.println("Copy Array 3:"); System.arraycopy(sourceArray2, 0, targetArray2, 0, sourceArray2.length); System.out.println(targetArray2[i]); } //end main } //end class CopyingArray Program Output:

59 Passing Arrays to Methods
public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } Invoke the method int[] list = {3, 1, 2, 6, 4, 2}; printArray(list); Invoke the method printArray(new int[]{3, 1, 2, 6, 4, 2}); Anonymous array Based on these information, write the complete program

60 Passing Arrays to Methods
1. public class TprintArray { public static void main (String args[]) { int[] list = {3, 1, 2, 6, 4, 2}; printArray(list); } public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); 2. public class TprintArray { public static void main (String args[]) { printArray(new int[]{3, 1, 2, 6, 4, 2}); } public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); Program Output:

61 Anonymous Array The statement
printArray(new int[]{3, 1, 2, 6, 4, 2}); creates an array using the following syntax: new dataType[]{literal0, literal1, ..., literalk}; There is no explicit reference variable for the array. Such array is called an anonymous array.

62 Pass By Value Java uses pass by value to pass parameters to a method. There are important differences between passing a value of variables of primitive data types and passing arrays. For a parameter of a primitive type value, the actual value is passed. Changing the value of the local parameter inside the method does not affect the value of the variable outside the method. For a parameter of an array type, the value of the parameter contains a reference to an array; this reference is passed to the method. Any changes to the array that occur inside the method body will affect the original array that was passed as the argument.

63 Simple Example public class Test {
public static void main(String[] args) { int x = 1; // x represents an int value int[] y = new int[10]; // y represents an array of int values m(x, y); // Invoke m with arguments x and y System.out.println("x is " + x); System.out.println("y[0] is " + y[0]); } public static void m(int number, int[] numbers) { number = 1001; // Assign a new value to number numbers[0] = 5555; // Assign a new value to numbers[0]

64 Call Stack When invoking m(x, y), the values of x and y are passed to number and numbers. Since y contains the reference value to the array, numbers now contains the same reference value to the same array.

65 Heap The JVM stores the array in an area of memory, called heap, which is used for dynamic memory allocation where blocks of memory are allocated and freed in an arbitrary order.

66 Example: Passing Arrays as Arguments
Objective: Demonstrate differences of passing primitive data type variables and array variables.

67 Example:Passing Arrays as Arguments
public class TestPassArray { /** Main method */ public static void main(String[] args) { int[] a = {1, 2}; // Swap elements using the swap method System.out.println("Before invoking swap"); System.out.println("array is {" + a[0] + ", " + a[1] + "}"); swap(a[0], a[1]); System.out.println("After invoking swap"); // Swap elements using the swapFirstTwoInArray method System.out.println("Before invoking swapFirstTwoInArray"); swapFirstTwoInArray(a); System.out.println("After invoking swapFirstTwoInArray"); } /** Swap two variables */ public static void swap(int n1, int n2) { int temp = n1; n1 = n2; n2 = temp; /** Swap the first two elements in the array */ public static void swapFirstTwoInArray(int[] array) { int temp = array[0]; array[0] = array[1]; array[1] = temp; Program Output:

68 Example, cont.

69 Returning an Array from a Method
public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; list result int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1);

70 Trace the reverse Method
animation Trace the reverse Method int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); Declare result and create array public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; list 1 2 3 4 5 6 result

71 Trace the reverse Method, cont.
animation Trace the reverse Method, cont. int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); i = 0 and j = 5 public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; list 1 2 3 4 5 6 result

72 Trace the reverse Method, cont.
animation Trace the reverse Method, cont. int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); i (= 0) is less than 6 public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; list 1 2 3 4 5 6 result

73 Trace the reverse Method, cont.
animation Trace the reverse Method, cont. int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); i = 0 and j = 5 Assign list[0] to result[5] public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; list 1 2 3 4 5 6 result 1

74 Trace the reverse Method, cont.
animation Trace the reverse Method, cont. int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); After this, i becomes 1 and j becomes 4 public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; list 1 2 3 4 5 6 result 1

75 Trace the reverse Method, cont.
animation Trace the reverse Method, cont. int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); i (=1) is less than 6 public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; list 1 2 3 4 5 6 result 1

76 Trace the reverse Method, cont.
animation Trace the reverse Method, cont. int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); i = 1 and j = 4 Assign list[1] to result[4] public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; list 1 2 3 4 5 6 result 2 1

77 Trace the reverse Method, cont.
animation Trace the reverse Method, cont. int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); After this, i becomes 2 and j becomes 3 public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; list 1 2 3 4 5 6 result 2 1

78 Trace the reverse Method, cont.
animation Trace the reverse Method, cont. int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); i (=2) is still less than 6 public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; list 1 2 3 4 5 6 result 2 1

79 Trace the reverse Method, cont.
animation Trace the reverse Method, cont. int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); i = 2 and j = 3 Assign list[i] to result[j] public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; list 1 2 3 4 5 6 result 3 2 1

80 Trace the reverse Method, cont.
animation Trace the reverse Method, cont. int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); After this, i becomes 3 and j becomes 2 public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; list 1 2 3 4 5 6 result 3 2 1

81 Trace the reverse Method, cont.
animation Trace the reverse Method, cont. int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); i (=3) is still less than 6 public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; list 1 2 3 4 5 6 result 3 2 1

82 Trace the reverse Method, cont.
animation Trace the reverse Method, cont. int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); i = 3 and j = 2 Assign list[i] to result[j] public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; list 1 2 3 4 5 6 result 4 3 2 1

83 Trace the reverse Method, cont.
animation Trace the reverse Method, cont. int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); After this, i becomes 4 and j becomes 1 public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; list 1 2 3 4 5 6 result 4 3 2 1

84 Trace the reverse Method, cont.
animation Trace the reverse Method, cont. int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); i (=4) is still less than 6 public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; list 1 2 3 4 5 6 result 4 3 2 1

85 Trace the reverse Method, cont.
animation Trace the reverse Method, cont. int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); i = 4 and j = 1 Assign list[i] to result[j] public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; list 1 2 3 4 5 6 result 5 4 3 2 1

86 Trace the reverse Method, cont.
animation Trace the reverse Method, cont. int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); After this, i becomes 5 and j becomes 0 public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; list 1 2 3 4 5 6 result 5 4 3 2 1

87 Trace the reverse Method, cont.
animation Trace the reverse Method, cont. int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); i (=5) is still less than 6 public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; list 1 2 3 4 5 6 result 5 4 3 2 1

88 Trace the reverse Method, cont.
animation Trace the reverse Method, cont. int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); i = 5 and j = 0 Assign list[i] to result[j] public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; list 1 2 3 4 5 6 result 6 5 4 3 2 1

89 Trace the reverse Method, cont.
animation Trace the reverse Method, cont. int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); After this, i becomes 6 and j becomes -1 public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; list 1 2 3 4 5 6 result 6 5 4 3 2 1

90 Trace the reverse Method, cont.
animation Trace the reverse Method, cont. int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); i (=6) < 6 is false. So exit the loop. public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; list 1 2 3 4 5 6 result 6 5 4 3 2 1

91 Trace the reverse Method, cont.
animation Trace the reverse Method, cont. int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); Return result public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; list 1 2 3 4 5 6 list2 result 6 5 4 3 2 1

92 Example: Program to Reverse An Array
public class Reversing { public static void main (String args[]) { int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; int[] list2 = reverse(list1); displaying(list2); } public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; return result; public static void displaying(int[] list) { for (int i = 0; i < list.length; i++) System.out.println(list[i] + " "); Program Output:

93 Exercise Write a program that sends a list of array elements 1, 2, 3, 4, 5 typed integer to method changeArray and returns a list of array elements 3, 4, 5, 6, 7 typed integer to the main method that is assigned to an array. Then, the array is sent to the displaying method for printing. The output is as follows:

94 Solution public class ChangingArrayValue {
public static void main (String args[]) { int[] list1 = {1, 2, 3, 4, 5}; System.out.println("Array before change: "); displaying(list1); int[] list2 = changeArray(list1); System.out.println("Array after change: "); displaying(list2); } public static int[] changeArray(int[] list) { for (int i = 0; i < list.length; i++) { list[i] = list[i] // or list[i] = i+3; return list; public static void displaying(int[] list) { for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); System.out.println();

95 Example: Counting Occurrence of Each Letter
Generate 100 lowercase letters randomly and assign to an array of characters. Count the occurrence of each letter in the array.

96 Example: Counting Occurrence of Each Letter
public class CountLettersInArray { /** Main method */ public static void main(String args[]) { // Declare and create an array char[] chars = createArray(); // Display the array System.out.println("The lowercase letters are:"); displayArray(chars); // Count the occurrences of each letter int[] counts = countLetters(chars); // Display counts System.out.println(); System.out.println("The occurrences of each letter are:"); displayCounts(counts); } /** Create an array of characters */ public static char[] createArray() { // Declare an array of characters and create it char[] chars = new char[100]; // Create lowercase letters randomly and assign // them to the array for (int i = 0; i < chars.length; i++) chars[i] = RandomCharacter.getRandomLowerCaseLetter(); // Return the array return chars; /** Display the array of characters */ public static void displayArray(char[] chars) { // Display the characters in the array 20 on each line for (int i = 0; i < chars.length; i++) { if ((i + 1) % 20 == 0) System.out.println(chars[i] + " "); else System.out.print(chars[i] + " "); } /** Count the occurrences of each letter */ public static int[] countLetters(char[] chars) { // Declare and create an array of 26 int int[] counts = new int[26]; // For each lowercase letter in the array, count it for (int i = 0; i < chars.length; i++) counts[chars[i] - 'a']++; return counts; /** Display counts */ public static void displayCounts(int[] counts) { for (int i = 0; i < counts.length; i++) { if ((i + 1) % 10 == 0) System.out.println(counts[i] + " " + (char)(i + 'a')); System.out.print(counts[i] + " " + (char)(i + 'a') + " ");

97 Example: Counting Occurrence of Each Letter: RandomCharacter Class
public class RandomCharacter { /** Generate a random character between ch1 and ch2 */ public static char getRandomCharacter(char ch1, char ch2) { return (char)(ch1 + Math.random() * (ch2 - ch1 + 1)); } /** Generate a random lowercase letter */ public static char getRandomLowerCaseLetter() { return getRandomCharacter('a', 'z'); /** Generate a random uppercase letter */ public static char getRandomUpperCaseLetter() { return getRandomCharacter('A', 'Z'); /** Generate a random digit character */ public static char getRandomDigitCharacter() { return getRandomCharacter('0', '9'); /** Generate a random character */ public static char getRandomCharacter() { return getRandomCharacter('\u0000', '\uFFFF');

98 Example: Counting Occurrence of Each Letter: Program Output

99 Exercise Write a complete Java program that passes a student name (String), Ali; matric (String), 12345; and an array (integer) consisting of 3 test marks, 68, 78 and 88 to a method named studInfo, that does not return any value. The operation inside the method is to print the student’s info as follows:

100 Solution public class PrintInfo {
public static void main (String args[]) { int[] testscore = {68,78,88}; studentInfo("Ali","12345",testscore); } public static void studentInfo(String name,String matric,int[] array) { System.out.println("Student Test Info: "); System.out.println(); System.out.println("Name" +"\t" +"Matric" +"\t" +"Test 1" +"\t" +"Test 2" +"\t" +"Test 3"); System.out.println("====" +"\t" +"======" +"\t" +"======" +"\t" +"======" +"\t" +"======"); System.out.println(name +"\t" +matric +"\t" +array[0] +"\t" +array[1] +"\t" +array[2]);

101 Exercise Write a program that passes an array consisting of 7 elements of type integer to a method called calculateArray that returns the sum of the array elements. Example of output from command line if the array is 1,2,3,4,5,6,7 is: The sum of array elements is 28

102 Solution public class PassingArray {
public static void main (String args[]) { int[] list = {1,2,3,4,5,6,7}; System.out.println("The sum of array elements is " +calculateArray(list)); } public static int calculateArray(int[] array) { int sum=0; for (int i = 0; i < array.length; i++) sum+=array[i]; return sum;

103 Exercise Write a program that passes an array {4,5,8,9,12,13,16} of type integer to a method called divisorOfFour that counts the number of array elements that can be divided by 4. Example of output from command line is: There are 4 numbers that can be divided by 4

104 Solution public class CountDivisor {
public static void main (String args[]) { int[] list = {4,5,8,9,12,13,16}; int count = divisorOfFour(list); System.out.println("There are " +count +" numbers that can be divided by 4"); } public static int divisorOfFour(int[] list) { int count=0; for (int i = 0; i < list.length; i++) { if (list[i]%4==0) count++; return count;

105 Searching Arrays Searching is the process of looking for a specific element in an array; for example, discovering whether a certain score is included in a list of scores. Searching is a common task in computer programming. There are many algorithms and data structures devoted to searching. One of them is the linear search, others is the binary search

106 Linear Search The linear search approach compares the key element, key, sequentially with each element in the array list. The method continues to do so until the key matches an element in the list or the list is exhausted without a match being found. If a match is made, the linear search returns the index of the element in the array that matches the key. If no match is found, the search returns -1.

107 Linear Search Animation
Key List 3 6 4 1 9 7 3 2 8 3 6 4 1 9 7 3 2 8 3 6 4 1 9 7 3 2 8 3 6 4 1 9 7 3 2 8 3 6 4 1 9 7 3 2 8 3 6 4 1 9 7 3 2 8

108 From Idea to Solution Trace the method
/** The method for finding a key in the list */ public static int linearSearch(int[] list, int key) { for (int i = 0; i < list.length; i++) if (key == list[i]) return i; return -1; } Trace the method int[] list = {1, 4, 4, 2, 5, -3, 6, 2}; int i = linearSearch(list, 4); // returns 1 int j = linearSearch(list, -4); // returns -1 int k = linearSearch(list, -3); // returns 5

109 Linear Search Program Program Output: public class LinearSearching {
public static void main (String[] args) { int[] list = {1, 4, 4, 2, 5, -3, 6, 2}; int i = linearSearch(list, 4); int j = linearSearch(list, -4); int k = linearSearch(list, -3); System.out.println("The key is at index " +i); System.out.println("The key is at index " +j); System.out.println("The key is at index " +k); } /** The method for finding a key in the list */ public static int linearSearch(int[] list, int key) { for (int i = 0; i < list.length; i++) if (key = = list[i]) return i; return -1; Program Output:

110 Exercise Write a program that passes an array {“Ali”,”Ahmad”,”Aminah”,”Choong”,”David”} of type String to a method called searchName that searches the name “Aminah”, “Arumugam” and “David” in the array, which is the key. searchName method should return a String value. The output is as follows:

111 Solution public class LinearSearching {
public static void main (String[] args) { String[] list = {"Ali", "Ahmad", "Aminah", "Choong", "David"}; String i = linearSearch(list, "Aminah"); String j = linearSearch(list, "Arumugam"); String k = linearSearch(list, "David"); System.out.println(i); System.out.println(j); System.out.println(k); } /** The method for finding a key in the list */ public static String linearSearch (String[] list, String key) { for (int i = 0; i < list.length; i++) { if (key == list[i]) return key + " is found in the list!"; return key + " is not found in the list!";

112 Sorting Arrays Sorting, like searching, is also a common task in computer programming. It would be used, for instance, if you wanted to display the grades from the previous AssignGrade.java example, in alphabetical order. Many different algorithms have been developed for sorting. One of them is the selection sort algorithm, others is the insertion sort algorithm.

113 Selection Sort Selection sort finds the largest number in the list and places it last. It then finds the largest number remaining and places it next to last, and so on until the list contains only a single number. Next figure shows how to sort the list {2, 9, 5, 4, 8, 1, 6} using selection sort.

114 animation Selection Sort int[] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted 2 9 5 4 8 1 6 2 6 5 4 8 1 9 2 6 5 4 1 8 9 2 1 5 4 6 8 9 2 1 4 5 6 8 9 2 1 4 5 6 8 9 1 2 4 5 6 8 9

115 From Idea to Solution for (int i = list.length - 1; i >= 1; i--) {
select the largest element in list[0..i]; swap the largest with list[i], if necessary; // list[i] is in place. The next iteration applies on list[0..i-1] } list[0] list[1] list[2] list[3] list[10] list[0] list[1] list[2] list[3] list[9] list[0] list[1] list[2] list[3] list[8] list[0] list[1] list[2] list[3] list[7] ... list[0]

116 Expand for (int i = list.length - 1; i >= 1; i--) {
select the largest element in list[0..i]; swap the largest with list[i], if necessary; // list[i] is in place. The next iteration applies on list[0..i-1] } Expand // Find the maximum in the list[0..i] double currentMax = list[0]; int currentMaxIndex = 0; for (int j = 1; j <= i; j++) { if (currentMax < list[j]) { currentMax = list[j]; currentMaxIndex = j; }

117 Expand for (int i = list.length - 1; i >= 1; i--) {
select the largest element in list[0..i]; swap the largest with list[i], if necessary; // list[i] is in place. The next iteration applies on list[0..i-1] } Expand // Find the maximum in the list[0..i] double currentMax = list[0]; int currentMaxIndex = 0; for (int j = 1; j <= i; j++) { if (currentMax < list[j]) { currentMax = list[j]; currentMaxIndex = j; }

118 Expand // Swap list[i] with list[currentMaxIndex] if necessary;
for (int i = list.length - 1; i >= 1; i--) { select the largest element in list[0..i]; swap the largest with list[i], if necessary; // list[i] is in place. The next iteration applies on list[0..i-1] } Expand // Swap list[i] with list[currentMaxIndex] if necessary; if (currentMaxIndex != i) { list[currentMaxIndex] = list[i]; list[i] = currentMax; }

119 Wrap it in a Method /** The method for sorting the numbers */
public static void selectionSort(double[] list) { for (int i = list.length - 1; i >= 1; i--) { // Find the maximum in the list[0..i] double currentMax = list[0]; int currentMaxIndex = 0; for (int j = 1; j <= i; j++) { if (currentMax < list[j]) { currentMax = list[j]; currentMaxIndex = j; } // Swap list[i] with list[currentMaxIndex] if necessary; if (currentMaxIndex != i) { list[currentMaxIndex] = list[i]; list[i] = currentMax;

120 Selection Sort Program
public class SelectionSort { /** Main method */ public static void main(String[] args) { // Initialize the list double[] myList = {5.0, 4.4, 1.9, 2.9, 3.4, 3.5}; // Print the original list System.out.println("My list before sort is: "); printList(myList); // Sort the list selectionSort(myList); // Print the sorted list System.out.println(); System.out.println("My list after sort is: "); } /** The method for printing numbers */ static void printList(double[] list) { for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); /** The method for sorting the numbers */ static void selectionSort(double[] list) { for (int i = list.length - 1; i >= 1; i--) { // Find the maximum in the list[0..i] double currentMax = list[0]; int currentMaxIndex = 0; for (int j = 1; j <= i; j++) { if (currentMax < list[j]) { currentMax = list[j]; currentMaxIndex = j; } // Swap list[i] with list[currentMaxIndex] if necessary; if (currentMaxIndex != i) { list[currentMaxIndex] = list[i]; list[i] = currentMax;

121 Selection Sort Program Output

122 Two-dimensional Arrays
// Declare array ref var dataType[][] refVar; // Create array and assign its reference to variable refVar = new dataType[10][10]; // Combine declaration and creation in one statement dataType[][] refVar = new dataType[10][10]; // Alternative syntax dataType refVar[][] = new dataType[10][10];

123 Declaring Variables of Two-dimensional Arrays and Creating Two-dimensional Arrays
int[][] matrix = new int[10][10]; or int matrix[][] = new int[10][10]; matrix[0][0] = 3; for (int i = 0; i < matrix.length; i++) for (int j = 0; j < matrix[i].length; j++) matrix[i][j] = (int)(Math.random() * 1000); double[][] x;

124 Two-dimensional Array Illustration
matrix.length? 5 (row) matrix[0].length? 5 (column) array.length? 4 (row) array[0].length? 3 (column)

125 Declaring, Creating, and Initializing Using Shorthand Notations
You can also use an array initializer to declare, create and initialize a two-dimensional array. For example, int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; int[][] array = new int[4][3]; array[0][0] = 1; array[0][1] = 2; array[0][2] = 3; array[1][0] = 4; array[1][1] = 5; array[1][2] = 6; array[2][0] = 7; array[2][1] = 8; array[2][2] = 9; array[3][0] = 10; array[3][1] = 11; array[3][2] = 12; Same as

126 Lengths of Two-dimensional Arrays
int[][] x = new int[3][4];

127 Lengths of Two-dimensional Arrays, cont.
int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; array.length = 4 array[0].length = 3 array[1].length = 3 array[2].length = 3 array[3].length = 3 array[4].length ArrayIndexOutOfBoundsException

128 Ragged Arrays Each row in a two-dimensional array is itself an array. So, the rows can have different lengths. Such an array is known as a ragged array. For example, int[][] matrix = { {1, 2, 3, 4, 5}, {2, 3, 4, 5}, {3, 4, 5}, {4, 5}, {5} }; matrix.length is 5 matrix[0].length is 5 matrix[1].length is 4 matrix[2].length is 3 matrix[3].length is 2 matrix[4].length is 1

129 Ragged Arrays, cont.

130 Example: Grading Multiple-Choice Test
Objective: write a program that grades multiple-choice test.

131 Example: Grading Multiple-Choice Test Program
public class GradeExam { /** Main method */ public static void main(String args[]) { // Students' answers to the questions char[][] answers = { {'A', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'}, {'D', 'B', 'A', 'B', 'C', 'A', 'E', 'E', 'A', 'D'}, {'E', 'D', 'D', 'A', 'C', 'B', 'E', 'E', 'A', 'D'}, {'C', 'B', 'A', 'E', 'D', 'C', 'E', 'E', 'A', 'D'}, {'A', 'B', 'D', 'C', 'C', 'D', 'E', 'E', 'A', 'D'}, {'B', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'}, {'B', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D'}, {'E', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'}}; // Key to the questions char[] keys = {'D', 'B', 'D', 'C', 'C', 'D', 'A', 'E', 'A', 'D'}; // Grade all answers for (int i = 0; i < answers.length; i++) { // Grade one student int correctCount = 0; for (int j = 0; j < answers[i].length; j++) { if (answers[i][j] == keys[j]) correctCount++; } System.out.println("Student " + i + "'s correct count is " + correctCount); Program Output:

132 Exercise Write a program to calculate the average of five double numbers stored in an array: 1.0, 2.0, 3.0, 4.0, 5.0 and find how many numbers are above the average.

133 Exercise Solution Program Output: public class CalcAverage {
public static void main (String[] args) { double[] myList = {1.0, 2.0, 3.0, 4.0, 5.0}; System.out.print("The list is: "); printmyList(myList); calculateAvg(myList); } public static void printmyList(double[] array) { for (int i = 0; i < array.length; i++) System.out.print(array[i] + " "); System.out.println(" "); public static void calculateAvg(double[] array) { double sum = 0.0; double count = 0.0; double average; int count1 = 0; for (int i = 0; i < array.length; i++) { sum += array[i]; count++; average = sum/count; System.out.println("The average is: " +average); if (array[i]>average) count1++; System.out.println("Numbers above average is: " +count1); Program Output:

134 Exercise Write a program that reads 5 student’s matrix number in String data type and display all of them (Use JOptionPane).

135 Exercise Solution import javax.swing.JOptionPane;
public class Matrix { /** Main method */ public static void main(String[] args) { final int TOTAL_MATRIX = 5; String[] matrixnum = new String[TOTAL_MATRIX]; // Read all numbers for (int i = 0; i < matrixnum.length; i++) { String numString = JOptionPane.showInputDialog( "Enter student matrix number:"); matrixnum[i] = numString; } // Prepare the result String output = "The student matrix are "; output += matrixnum[i] + " "; // Display the result JOptionPane.showMessageDialog(null, output);


Download ppt "Chapter 7 Arrays."

Similar presentations


Ads by Google