Lesson 9: Introduction To Arrays - Clausen Tech

2y ago
24 Views
2 Downloads
680.50 KB
79 Pages
Last View : 12d ago
Last Download : 3m ago
Upload by : Rosa Marty
Transcription

Lesson 9:Introduction ToArrays(Updated for Java 1.5Modifications by Mr. Dave Clausen)1

Lesson 9: IntroductionTo ArraysObjectives: Write programs that handle collectionsof similar items.Declare array variables and instantiatearray objects.Manipulate arrays with loops, includingthe enhanced for loop.Write methods to manipulate arrays.Create parallel arrays and twodimensional arrays.2

Lesson 9: IntroductionTo ArraysVocabulary: arrayelementindexinitializer listlogical cture chart parallel arraysphysical sizeragged arrayrange bound errorsubscripttwo-dimensionalarrayEnhanced for loopProceduraldecomposition3

9.1 Conceptual Overview An array consists of an ordered collection ofsimilar items.An array has a single name, and the items in anarray are referred to in terms of their positionwithin the array.An array makes it is as easy to manipulate amillion test scores as it is to manipulate threetest scores.Once an array is declared, its size is fixed andcannot be changed.4

9.1 Conceptual Overview Without arrays, a program with 20 testscores would look like this:private String name;private int test1, test2,test6, test7,test11, test12,test16, 4,test19,test5,test10,test15,test20;5

9.1 Conceptual Overview And the computation of the averagescore looks like this:// Compute and return a student’s averagepublic int getAverage(){int average;average (test1 test2 test3 test4 test5 test6 test7 test8 test9 test10 test11 test12 test13 test14 test15 test16 test17 test18 test19 test20) / 20;return average;}6

9.1 Conceptual Overview The items in an array are called elements.For any particular array, all the elements mustbe of the same type.The type can be any primitive or reference type. For instance, we can have an array of test scores(integers), an array of names (Strings), or even anarray of student objects.In figure 9-1 each array contains five elements, or hasa length of five.Remember that Java starts counting with 0 rather than17

9.1 Conceptual Overview The first element in the array test is referred to as test[0], thesecond as test[1], and so on.An item's position within an array is called its index orsubscript.Array indexes appear within square brackets [ ]8

9.2 Simple ArrayManipulations First we declare and instantiate anarray of 500 integer values.By default, all of the values are initializedto 0:int[] abc new int[500]; Next, we declare some other variables:int i 3;int temp;double avFirstFive;9

9.2 Simple ArrayManipulations The basic syntax for referring to an arrayelement has the form: array name [ index ] Where index must be between 0 andthe array's length less 1.The subscript operator ([ ]) has the sameprecedence as the method selector (.).10

9.2 Simple ArrayManipulations For example we assign values to the firstfive elements:abc[0] 78;//1stabc[1] 66;//2ndabc[2] (abc[0] abc[1]) / 2; //3rdabc[i] 82;//4thabc[i 1] 94;//5th elementelementelementelementelement7866average of first two82 because i is 394 because i 1 is 4When assigning a value to the 500thelement, we must remember that itsindex is 499, not 500:abc[499] 76;//500th element 7611

9.2 Simple ArrayManipulations The JVM checks the values of subscripts beforeusing them and throws anArrayIndexOutOfBoundsException if they areout of bounds (less than 0 or greater than thearray length less 1).The detection of a range bound error issimilar to the JVM's behavior when a programattempts to divide by 0.To compute the average of the first fiveelements, we could write:avFirstFive (abc[0] abc[1] abc[2] abc[3] abc[4])/5;12

9.2 Simple ArrayManipulations It often happens that we need tointerchange elements in an array.(the basic idea behind a simple sort)// Initializations. . .abc[3] 82;abc[4] 95;i 3;. . .// Interchange adjacent elementstemp abc[i];abc[i] abc[i 1];abc[i 1] temp;// temp// abc[i]// abc[i 1]now equals 82now equals 95now equals 8213

9.2 Simple ArrayManipulations We frequently need to know an array'slength.The array itself makes this informationavailable by means of a public instancevariable called length:System.out.println ("The size of abc is: " abc.length);//Just abc.length, no ( ) are used with the length variable//In C , length was a function and required ( )14

9.3 Looping Through ArraysSum the Elements The following code sums the numbers in thearray abc.Each time through the loop adds a differentelement to the sum. On the first iteration weadd abc[0] and on the last abc[499].int sum;sum 0;for (int i 0; i 500; i )sum abc[i];15

9.3 Looping Through ArraysCount the Occurrences We can determine how many times a number xoccurs in the array by comparing x to eachelement and incrementing count every timethere is a match:int x;int count;x .;count 0;for (int i 0; i 500; i ){if (abc[i] x)count ;}//Assign some value to x//Found another element equal to x16

9.3 Looping Through ArraysDetermine Presence or Absence To determine if a particular number ispresent in the array, programmers canend the loop as soon as the first match isfound, using indefinite (while) loops.The Boolean variable found indicates theoutcome of the search.17

9.3 Looping Through ArraysDetermine absence or presenceSource code w/o break statement as opposed to Page 309int x, counter 0;boolean notFound true;x .; //number to search forwhile ((counter list.length) && notFound ){if (list[counter] x)notFound false;counter ;}if (notFound)System.out.println (“Not Found”);elseSystem.out.println (“Found”);18

9.3 Looping Through ArraysDetermine first locationSource code w/o break statement as opposed to Page 310int x, counter 0,location 0;boolean notFound true;x .; //number to search forwhile ((counter list.length) && notFound ){if (list[counter] x){location counter;notFound false;}counter ;}if (notFound)System.out.println (“Not Found”);elseSystem.out.println (“Found at index # ” location);19

9.3 Looping Through ArraysWorking With Arrays of Any Size It is possible and also desirable to write codethat works with arrays of any size.Simply replace the literal 500 with a reference tothe array's instance variable length in each ofthe loops.For example, this code would sum the integersin an array of any size:int sum;sum 0;for (int i 0; i abc.length; i )sum abc[i];20

9.4 Declaring Arrays Arrays are objects and must beinstantiated before being used.Several array variables can be declared ina single statement like this:int[] abc, xyz;abc new int[500];xyz new int[10]; Or like this:int[] abc new int[500];int[] xyz new int[10];21

9.4 Declaring Arrays Array variables are null before they areassigned array objects.Failure to assign an array object canresult in a null pointer exception.int[] abc;abc[1] 10; // runtime error: null pointer exception22

9.4 Declaring ArraysBecause arrays are objects, all rulesthat apply to objects apply to arrays. Two array variables may refer to samearray.Arrays may be garbage collected.Array variables may be set to null.Arrays are passed by reference tomethods.23

9.4 Declaring Arrays Because arrays are objects, two variablescan refer to the same array as indicatedin Figure 9-2 and the next segment ofcode:int[] abc, xyz;abc new int[5];xyz abc;// Instantiate an array of 5 integers// xyz and abc refer (point) to the same// array, they are not duplicate arraysxyz[3] 100;// Changing xyzSystem.out.println (abc[3]);changes abc as well.// 10 { 0, 1, 2, 3, 34}};////////rowrowrowrow012363

9.7 Two-Dimensional ArraysVariable Length Rows Ragged arrays are rows of a two-dimensional arrays that are not all thesame length.int[][] table;table newtable[0] newtable[1] newtable[2] newtable[3] ///tablerow 0row 1row 2row 3hashashashashas4 rows6elements10 elements100 elements1element64

9.8 The Enhanced for LoopProvided in Java 5.0 to simplify loops inwhich each element in an array isaccessed From the first index to the lastFrees programmer from having tomanage and use loop countersSyntax:65

9.8 The Enhanced for LoopExample 9.3: Testing the enhanced for loopTestForLoop.javaTestForLoop.txt66

9.8 The Enhanced for LoopCannot be used to: Move through an array in reverse, fromthe last position to the first positionAssign elements to positions in an arrayTrack the index position of the currentelement in an arrayAccess any element other than thecurrent element on each pass67

9.10 Arrays of Objects Arrays can hold objects of any type, ormore accurately, references to objects.For example, one can declare, instantiateand fill an array of students as follows:// Declare and reserve 10 cells for student objectsStudent[] studentArray new Student[10];// Fill array with studentsfor (int i 0; i studentArray.length; i )studentArray[i] new Student("Student " i, 70 i, 80 i, 90 i);68

9.10 Arrays of Objects When an array of objects is instantiated, eachcell is null by default until reset to a new object.The next code segment prints the average of allstudents in the studentArray. Pay specialattention to the technique used to send amessage to objects in an array:// Print the average of all students in the array.int sum 0;for (int i 0; i studentArray.length; i )sum studentArray[i].getAverage();// Send message to object in arraySystem.out.println("The class average is " sum / accountArray.length);69

Case Study Design TechniquesUML diagrams: Industry standard fordesigning and representing a set ofinteracting classesStructure charts: May be used to depictrelationships between classes and the orderof methods called in a programProcedural decomposition: Technique ofdividing a problem into sub-problems andcorrelating each with a method70

Case Study Design Techniques(cont.)Figure 9-6: UML diagram of the classes in the student testscores program71

Case Study Design Techniques(cont.)Figure 9-7: Structure chart for the methods of classTestScoresView72

Case oresView.javaTestScoresView.txt73

Design, Testing, andDebugging HintsTo create an array: 1. Declare an array variable.2. Instantiate an array object and assign it to thearray variable.3. Initialize the cells in the array with data, asappropriate.When creating a new array object, try todetermine an accurate estimate of thenumber of cells required.74

Design, Testing, andDebugging Hints (cont.)Remember that array variables are null untilthey are assigned array objects.To avoid index out-of-bounds errors,remember that the index of an array cellranges from 0 (the first position) to thelength of the array minus 1.To access the last cell in an array, use theexpression array .length – 1.75

Design, Testing, andDebugging Hints (cont.)Avoid having multiple array variables refer tothe same array.To copy the contents of one array to another,do not use A B; instead, write a copymethod and use A arrayCopy(B);.When an array is not full: Track the current number of elementsAvoid index out-of-bounds errors76

SummaryArrays are collections of similar items orelements ordered by position.Arrays are useful when a program needs tomanipulate many similar items, such as agroup of students or a number of test scores.Arrays are objects. Must be instantiatedCan be referred to by more than one variable77

Summary (cont.)An array can be passed to a method asa parameter and returned as a value.Parallel arrays are useful for organizinginformation with correspondingelements.Two-dimensional arrays store values ina row-and-column arrangement.78

Summary (cont.)An enhanced for loop is a simplifiedversion of a loop for visiting eachelement of an array from the firstposition to the last position.79

2 Lesson 9: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array variables and instantiate array objects. Manipulate arrays with loops, including the enhanced for loop. Write methods to manipulate arrays. Create parallel arrays and two- dimensional arrays.

Related Documents:

Hooray for Arrays: A Mini Reference Guide Hooray for Arrays: What Do You Say, Let's Make an Array! * Hooray for Arrays: Repeat Addition * Hooray for Arrays: Multiplication Fact Practice * Hooray for Arrays: Equal Group Problems * Hooray for Arrays: Repeated Addition and Multiplication * Hooray for Arrays:

4 Step Phonics Quiz Scores Step 1 Step 2 Step 3 Step 4 Lesson 1 Lesson 2 Lesson 3 Lesson 4 Lesson 5 Lesson 6 Lesson 7 Lesson 8 Lesson 9 Lesson 10 Lesson 11 Lesson 12 Lesson 13 Lesson 14 Lesson 15 . Zoo zoo Zoo zoo Yoyo yoyo Yoyo yoyo You you You you

Super Teacher Worksheets - www.superteacherworksheets.com 1. Arrays Arrays 3. Arrays 4. Arrays 2. Write a multiplication fact that is shown by the array. Write a multiplication fact that is shown by the array. Mr. Rule is a 4th grade teacher. He sets up 4 rows of desks in his classroom. Each

Arrays in Java Arrays in Java are objects Only 1D arrays are directly supported Multidimensional arrays are arrays of arrays General, but slow - due to memory layout, difficulty of compiler analysis, and bounds checking Subarrays are important in AMR (e.g., interior of a grid) – Even C and C don’t support these well

Lesson 13: Fives arrays 54 Lesson 14: Fives - sharing and grouping 57 Lesson 15: Twos and repeated addition 60 Lesson 16: Twos arrays 63 Week 6 66 Lesson 17: Twos - sharing and grouping 66 Lesson 18: 2-D shapes 69 Lesson 19: 2-D shapes: straight or round edges 72 Lesson 20: Data - tally tables 75 Week 7 78

Participant's Workbook Financial Management for Managers Institute of Child Nutrition iii Table of Contents Introduction Intro—1 Lesson 1: Financial Management Lesson 1—1 Lesson 2: Production Records Lesson 2—1 Lesson 3: Forecasting Lesson 3—1 Lesson 4: Menu Item Costs Lesson 4—1 Lesson 5: Product Screening Lesson 5—1 Lesson 6: Inventory Control Lesson 6—1

Search an array and use parallel arrays Pass arrays to and return arrays from methods . In Java, you can also declare an array variable by placing the square brackets after the array name, as in . but Java programmers conventionally name arrays by following the same rules they use for variables—array names start with a lowercase letter .

Kesehatan merupakan investasi sumber daya manusia dan merupakan tanggung jawab bersama. Pesantren merupakan salah satu lembaga pendidikan agama Islam yang akan menghasilkan manusia yang berkualitas. Untuk meningkatkan kualitas hidup sumber daya manusia di pesantren, maka diharapkan lembaga pendidikan pondok pesantren termasuk komunitas pesantren, yang berisiko tinggi untuk terjangkit penyakit .