E N D
Chapter 6 Arrays Spring 2013
Motivations Often you will have to store a large number of values during the execution of a program. Suppose, for instance, that you need to read one hundred numbers, compute their average, and find out how many numbers are above the average. Your program first reads the numbers and computes their average, and then compares each number with the average to determine whether it is above the average. The numbers must all be stored in variables in order to accomplish this task. You have to declare one hundred variables and repeatedly write almost identical code one hundred times. From the standpoint of practicality, it is impossible to write a program this way. So, how do you solve this problem?
Objectives • To describe why arrays are necessary in programming (§6.1). • To learn the steps involved in using arrays: declaring array reference variables and creating arrays (§§6.2.1-6.2.2). • To initialize the values in an array (§6.2.3). • To access array elements using indexed variables (§6.2.4). • To simplify programming using the JDK 1.5 foreach loops (§6.2.5). • To declare, create, and initialize an array using an array initializer (§6.2.6). • To copy contents from one array to another (§6.3). • To develop and invoke methods with array arguments and return value (§6.4-6.5). • To declare a method with variable-length argument list (§6.6). • To search elements using the linear (§6.7.1) or binary (§6.7.2) search algorithm. • To sort an array using the selection sort (§6.8.1) • To sort an array using the insertion sort algorithm (§6.8.2). • To use the methods in the Arrays class (§6.9). • To declare and create two-dimensional arrays to solve interesting problems such as Sudoku (§6.10). • To declare and create multidimensional arrays (§6.11).
Introducing Arrays Array is a data structure that represents a collection of the same types of data.
Declaring Array Variables • datatype[] arrayRefVar; Example: double[] myList; • datatype arrayRefVar[]; // This style is allowed, but not preferred Example: double myList[];
Creating Arrays 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.
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];
The Length of an Array 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
Default Values When an array is created, its elements are assigned the default value of • 0 for the numeric primitive data types • short, int, long, float, double • '\u0000' for char types • false for boolean types.
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. For example: double[] myList = new double[10] 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]; myList[0], myList[1], myList[2], myList[3], myList[4], myList[5], myList[6], myList[7], myList[8], myList[9]
Default Values double[] mydouble = new double[5] Is initialized to: mydouble[0] = 0.0 mydouble[1] = 0.0 mydouble[2] = 0.0 mydouble[3] = 0.0 mydouble[4] = 0.0 int[] myInt = new int[5] Is initialized to: myInt[0] = 0 myInt[1] = 0 myInt[2] = 0 myInt[3] = 0 myInt[4] = 0 boolean[] myBool = new boolean[5]] Is initialized to: myBool[0] = false myBool[1] = false myBool[2] = false myBool[3] = false myBool[4] = false
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[0] = 5.0; myList[1] = 2.4; myList[2] = myList[0] + myList[1]; Will set MyList[2] = 7.4
Array Initializers • Declaring, creating, initializing in one step: double[] myList = {1.9, 2.9, 3.4, 3.5}; This shorthand syntax must be in one statement.
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;
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};
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]; } }
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]; } } i 1
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]; } } i 1
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]; } } i 1 values[1] = 1 + values[0] Values[1 = 1 + 0
animation Trace Program with Arrays 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]; } } After i++, i becomes 2 i 2
animation Trace Program with Arrays 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]; } } i (= 2) is less than 5 i 2
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]; } } i 2 values[2] = 2 + values[1] Values[2] = 2 + 1
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]; } } i 3
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]; } } i 3
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]; } } values[3] = 3 + values[2] Values[3] = 3 + 3 i 3
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]; } } i 4
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]; } } i 4
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]; } } values[4] = 4 + values[3] Values[4] = 4 + 6 i 4
animation Trace Program with Arrays 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]; } } After i++, i becomes 5 i 5
animation Trace Program with Arrays 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]; } } i ( =5) < 5 is false. Exit the loop i 5
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]; } } values[0] = 1 + 10
Processing Arrays See the examples in the text. • (Initializing arrays) • (Printing arrays) • (Summing all elements) • (Finding the largest element) • (Finding the smallest index of the largest element) • (Shifting elements)
Initializing Arrays Initializing arrays with random values: The following loop initializes the array myList with random values between 0.0 and 100.0, but less than 100.0. for ( int i = 0; i < myList. length; i++) { myList[ i] = Math. random() * 100; }
Printing Arrays To print an array, you have to print each element in the array using a loop like the following: for ( int i = 0; i < myList. length; i++) { System. out. print( myList[ i] + " "); } For an array of the char[] type, it can be printed using one print statement. For example, the following code displays Dallas: char[] city = {' D', ' a', ' l', ' l', ' a', ' s'}; System.out.println( city);
Summing all elements Use a variable named total to store the sum. Initially total is 0. Add each element in the array to total using a loop like this: double total = 0; for ( int i = 0; i < myList. length; i++) { total += myList[ i]; }
Finding the largest element Use a variable named max to store the largest element. Initially max is myList[ 0]. To find the largest element in the array myList, compare each element in myList with max, and update max if the element is greater than max. double max = myList[ 0]; for ( int i = 1; i < myList. length; i++) { if ( myList[ i] > max) max = myList[ i]; }
Finding the smallest index of the largest element Often you need to locate the largest element in an array. If an array has more than one largest element, find the smallest index of such an element. Suppose the array myList is 1, 5, 3, 4, 5, 5 The largest element is 5 and the smallest index for 5 is 1. Use a variable named max to store the largest element and a variable named indexOfMax to denote the index of the largest element. Initially max is myList[ 0], and indexOfMax is 0. Compare each element in myList with max, and update max and indexOfMax if the element is greater than max. double max = myList[ 0]; int indexOfMax = 0; for ( int i = 1; i < myList. length; i++) { if (myList[i] > max) { max = myList[ i]; indexOfMax = i; } } What is the consequence if ( myList[ i] > max) is replaced by ( myList[ i] >= max)?
Shifting elements Sometimes you need to shift the elements left or right. Here is an example to shift the elements one position to the left and fill the last element with the first element: double temp = myList[ 0]; // Retain the first element // Shift elements left for ( int i = 1; i < myList. length; i++) { myList[ i - 1] = myList[ i]; } // Move the first element to fill in the last position myList[ myList. length - 1] = temp;
Enhanced for Loop (for-each loop) 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 } 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.
Example: Analyzing Array Elements • 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.
TestArray.java import java.util.Scanner; public class TestArray { /** Main method */ public static void main(String[] args) { final int TOTAL_NUMBERS = 6; int[] numbers = new int[TOTAL_NUMBERS]; // Create a Scanner Scanner input = new Scanner(System.in); // Read all numbers for (int i = 0; i < numbers.length; i++) { System.out.print("Enter a number: "); // Convert string into integer numbers[i] = input.nextInt(); }
TestArray.java // 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; for (int i = 0; i < numbers.length; i++) { if (numbers[i] == max) count++; }
TestArray.java // 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 System.out.println(output); } }
Problem: Assigning Grades • Objective: read student scores (int), get the best score, and then assign grades based on the following scheme: • 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.
AssignGrade.java import java.util.Scanner; public class AssignGrade { /** Main method */ public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); // Get number of students System.out.print("Please enter number of students: "); int numberOfStudents = input.nextInt(); 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++) { System.out.print("Please enter a score: "); scores[i] = input.nextInt(); if (scores[i] > best) best = scores[i]; }
AssignGrade.java // 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 System.out.println(output); } }
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: list2 = list1;
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];
The arraycopy Utility arraycopy(sourceArray, src_pos, targetArray, tar_pos, length); Example: System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);
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