1 / 46

CHAPTER 8 ARRAYS

CHAPTER 8 ARRAYS. This chapter in the book includes: 8.1 One-Dimensional Arrays 8.2 Array Initialization 8.3 Arrays and Arguments 8.4 Two-Dimensional Arrays 8.5 Common Programming Errors 8.6 Chapter Summary. Click the mouse to move to the next page. Use the ESC key to exit this chapter.

dennis
Download Presentation

CHAPTER 8 ARRAYS

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CHAPTER 8ARRAYS This chapter in the book includes: 8.1 One-Dimensional Arrays 8.2 Array Initialization 8.3 Arrays and Arguments 8.4 Two-Dimensional Arrays 8.5 Common Programming Errors 8.6 Chapter Summary Click the mouse to move to the next page. Use the ESC key to exit this chapter.

  2. Arrays Primitive scalar variables can contain a single value, like a one family house X Y Array Variables are more like an Apartment and may contain several elements with the same address, or location 3 2 1 0

  3. A simple list containing individual items of the same type is called a one dimensional array, or vector, or list. When the new operator is used to create storage for an array, the individual elements are automatically initialized: To zero for numerical types To false for boolean types and To null for reference types One Dimensional ARRAYS

  4. Figure 8.1: Three Lists of Items

  5. Figure 8.2: A List of Prices

  6. Figure 8.3: The Results of the Declaration double prices[];(Declaring an Array Creates a Reference Variable)

  7. Figure 8.4: The Results of the Allocationprices = new double[6];

  8. All elements in an array must be the same data type, that is all ints or all char, etc. Each item in the array is referred to as an element or component of the array. Array elements can be accessed all at once using a for loop or individually using the element’s index, subscript or position number. ( Example grade [4] or prices [2] ) The index of the beginning of an array is always zero. Array Elements

  9. Figure 8.5: The Arrays Referenced bygrade and code

  10. Figure 8.6: Identifying Individual Array Elements

  11. Figure 8.7: Accessing an Individual Array Element: Element 3

  12. Figure 8.8a: The Declaration String names[];Creates a Single Reference Variable

  13. Figure 8.8b: The Allocation names = new String[4] Creates an Array of References

  14. Figure 8.8c: The Assignment of Values Creates Actual Array Objects

  15. Figure 8.9: A Programming View of thenames Array

  16. public class StringArray { public static void main(String[] args) { int i; String names[ ]; // declare the array names = new String[4]; // allocate the array // assign values to each array element names[0] = "Joe"; names[1] = "Harriet"; names[2] = "Allyn"; names[3] = "Roberta"; // display the names for (i = 0; i < names.length; i++) System.out.println("names[" + i + "] is " + names[i]); } }

  17. The size of the array can be entered interactively by the user at run time. s1 = JOptionPane.showInputDialog( “How many grades?”); numgrades = Integer.parseInt( s1); int grade [ ] = new int[numgrades]; The size of the array depends on the value entered by the user Run Time Dimensioning

  18. Array elements can be initialized by: Including the elements in curly braces and NOT specifiying the size of the array int grade[] = {98,87,92,79,95}; Interactively using a for loop for ( i=0; i < grade.length; i++) grade [i] = 0; An array of characters cannot be initialized with a string char code [ ] = { ‘h’,’e’,’l’,’l’,’o’} //ok char code [ ] = “hello” // invalid Array Initialization

  19. public class InitializeNames { public static void main(String[] args) { int i; String names[] = {"Joe", "Harriet", "Allyn", Roberta"}; // display the names for (i = 0; i < names.length; i++) System.out.println("names[" + i + "] is " + names[i]); } }

  20. Searching a list sequentially means looking at each individual element in the list- You may want to count certain elements (for example: votes, positive numbers, honor grades, failures, etc.) You may just want to know if an item was in the list (for example: student in a class, sale item ,etc.) You may want the largest or smallest value. Searching

  21. public class FindMaxValue { public static void main(String[] args) { int i, max; int nums[] = {2, 18, 1, 27, 16}; max = nums[0]; // start with first value for (i = 1; i < nums.length; i++) if ( max < nums[i]) max = nums[i]; // store or “remember” largest System.out.println("The maximum value is " + max); } }

  22. Elements from one array can be copied into another array. System.arraycopy is a method that copies each element, one by one, from one array into a second array. The result is two distinct arrays. System.arraycopy requires 5 arguments System.arraycopy(source, startindex, target, start index, number of elements to copy) System.arraycopy (first,1,second,1, 3); Copying an Array

  23. Figure 8.10: Initial Allocation for the Arrays Declared in Program 8.7

  24. Figure 8.11: After the Call to System.arraycopy()(DEEP copy)

  25. Deep copy- copies a specified number (including the entire array) of elements from one array to another- it is an element by element copy System.arraycopy( nums, 1, newnums, 2, 3); Copies 3 elements from nums to newnums, beginning at element 1 an placing it in location 2 in new nums. Shallow copy- occurs when an array assignment is executed: newnums = nums; It copies the address stored in nums to newnums Deep and Shallow Copies

  26. public class DeepCopy //Program 8.7 { public static void main(String[ ] args) { int i, max; int nums[ ] = {2, 18, 1, 27, 16}; int newnums[ ] = new int[nums.length]; // copy all elements from nums to newnums System.arraycopy(nums, 0, newnums, 0, nums.length); // display newnums for (i = 0; i < newnums.length; i++) System.out.println( "newnums[" + i + "] is " + newnums[i]); newnums[2] = 50; // this only affects newnums System.out.println(); // display nums for (i = 0; i < nums.length; i++) System.out.println("nums[" + i + "] is " + nums[i]); } }

  27. Just using an assignment statement toassign the values of one array to an array with a different name produces surprising results. If list1 and list2 have been declared as arrays, we would expect that list2 = list1; would produce a second copy of the list. Does it? Shallow copies • No… instead it just assigns the address of list1 to list2 and both variables now reference the SAME list.

  28. Figure 8.12: The Result of the Shallow Copy Provided by Program 8.8

  29. public class ShallowCopy { public static void main(String[] args) { int i; int nums[ ] = {2, 18, 1, 27, 16}; int newnums[ ] = new int[nums.length]; // this produces a shallow copy newnums = nums; // this only copies the address // display newnums for (i = 0; i < newnums.length; i++) System.out.println("newnums[" + i + "] is " + newnums[i]); newnums[2] = 50; // affects both newnums and nums, because they are the same array System.out.println(); // display nums and note the change for (i = 0; i < nums.length; i++) System.out.println("nums[" + i + "] is " + nums[i]); } }

  30. Individual array elements are passed to methods in the same way as scalar variables. Individual elements are passed by value- the method receives a copy of the element, but cannot change it. Passing an entire array is easier- it is passed by reference- the method gets access to the actual array, it receives the address or location of the array Arrays as Arguments

  31. Figure 8.14: The Location of the Array is Passed

  32. Suppose you have this declaration: int nums[ ] = new int[5]; // list of 5 integers …and this method header int findMax(int val[ ]) Then you could pass this array to the method by findMax(nums) // notice- no [ ] Arrays as Arguments

  33. Figure 8.13: Only One Array is Created

  34. public class Array Argument { public static void main(String[] args) { int nums[ ] = {2, 18, 1, 27, 16}; // declare and initialize the array // call the method System.out.print("The maximum value is” + findMax(nums)); } // end main // This is the called method // It is used to find the maximum value stored in the array public static int findMax (int vals[ ]) { int I, max = val[0]; for (i = 0; i < vals.length; i++) if ( vals[i] < max ) max = vals[i]; return max; } // end findmax } // end class

  35. You can perform logical comparisons and arithmetic computation on individual array elements, for example: if grade[3] > grade [4] System.out.println( student[3] + “has the higher grade”); You can also perform operations on the entire array at once, using a for loop: for( i=0; i < grade.length; i++) grade[i] = grade[i] +5; Computing with Arrays

  36. public class MultiplyElements { public static void main(String[] args) {int i; int nums[ ] = {2, 18, 1, 27, 16}; changeValues(nums); // call the method // display the values System.out.print("The values in the nums array are"); for (i = 0; i < nums.length; i++) System.out.print(" " + nums[i]); }// multiply each element by 10 public static void changeValues(int vals[]) { int i; for (i = 0; i < vals.length; i++) vals[i] = 10*vals[i]; } }

  37. A two dimensional array, is called a table. It consists of rows and columns. To reserve storage for this array both the number of rows and the number of columns must be included in the declaration: int val[ ][ ] = new int[3] [4]; //3 rows, 4 columns or int val [ ] [ ] = { {8, 16, 9, 52}, {3, 15, 27, 6}, {7, 25, 2, 10}}; Two Dimensional Arrays

  38. Figure 8.15: Each Array Element Is Identified by Its Row and Column Position

  39. public class TableDisplay { public static void main(String[ ] args) { int i, j; int val[ ][ ] = {{8,16,9,52}, {3,15,27,6}, {7,25,2,10}}; System.out.print(“ \\nDisplay of val array by explicit element" +'\n' + val[0][0] + " " + val[0][1] + " " + val[0][2] + " " + val[0][3] +'\n' + val[1][0] + " " + val[1][1] + " " + val[1][2] + " " + val[1][3] +'\n' + val[2][0] + " " + val[2][1] + " " + val[2][2] + " " + val[2][3]); System.out.print("\n\nDisplay of val array using a nested for loop"); for (i = 0; i < val.length; i++) { System.out.print(‘ \ n‘ ); // print() a new line for each row for (j = 0; j < val[i].length; j++) System.out.print(val[i][j] + " "); } System.out.println( ); }

  40. public class MultipyByTen // This program multiplies each element in a 2-D table by 10 { public static void main(String[] args) { int i, j; int val[ ][ ] = {{8,16,9,52}, {3,15,27,6}, {7,25,2,10}}; // multiply each element by 10 and display it System.out.print("\n Display of multiplied elements"); for (i = 0; i < val.length; i++) { System.out.println( ); // start each row on a new line for (j = 0; j < val[i].length; j++) { val[i][j] = val[i][j] * 10; // multiply by 10 System.out.print(val[i][j] + " "); } // end of inner loop } // end of outer loop System.out.println(); } }

  41. Passing 2-D arrays is identical to passing a single- dimensional array. Because a reference is passed, the method receives access to the entire array, so any changes made to the array in the method is made directly to the array. Passing 2 Dimensional Arrays

  42. Public class PassTwodimensional { public static void main(String[] args) { int val[ ][ ] = {{8,16,9,52}, {3,15,27,6}, {7,25,2,10}}; display (val); // call just passes the indetifier } // end main public static void display(int nums[ ][ ]) //header shows 2 dimensions { int i, j; for (i = 0; i < nums.length; i++) { for(j = 0; j < nums[i].length; j++) System.out.print(nums[i][j] + " "); System.out.println(); } // end for } // end display method } // end class

  43. Java has the ability to create arrays in which each row has a different number of columns. Java also allows larger arrays with any number of dimensions. Rules for these larger dimensional arrays are the same as for single dimensions. ( See pp.326-79) Advanced Dimensions

  44. Figure 8.16: Representation of aThree-Dimensional Array

  45. Forgetting [ ] when declaring an array or in a method header Using [ ] in a method call Using a subscript value that references a non-existent array element (for example, declaring an array x of size 20 and using x[25] Using the wrong counter variables in the loop- or forgetting that arrays always begin with 0 Common Programming Errors

  46. Suppose you have 3 arrays declared as: int list[ ] = new int[5]; char tictactoe[ ] = new char [3][3]; Write headers and calls for methods: Sort the list Place character on the board to play game Header call Some Practice public static void sort (int list[ ] ) sort( list); public static void play (char tictactoe[ ] [ ]) play(tictactoe);

More Related