COMP 14 Introduction to ProgrammingArraysDeclaring ArraysDeclaring Arrays ExamplesInstantiating ArraysInstantiating Arrays ExamplesDeclaration and InstantiationExampleArray Access ExamplesArray LengthInitializing ArraysInitializer ListsArray BoundsSlide 14Slide 15Slide 16Slide 17Parallel ArraysIn-Class ExercisesSlide 20Slide 21ExercisesHomework 6 (practice)TomorrowCOMP 14Introduction to ProgrammingMiguel A. OtaduyJune 1, 2004Arrays•An array is a list of values that can be represented by one variable•Members of an array must all have the same data type•Each value is stored at a specific, numbered position in the array–the number corresponding to each position is called an index or subscript•All arrays have a length–number of elements the array can hold0 12 3Declaring Arraystype[] name;The array (element) data typeEmpty square bracketsThe array (variable) nameCreates a reference variable called name that can point to an array of type elements.0 12 3Declaring ArraysExamples// array of characterschar[] characterSet;// array of counters (integers)int[] counter;// array of grades (doubles)double[] grade;countercharacterSetgrade0 12 3Instantiating ArraysYou must instantiate (create) arrays–the size of an array is typically not known before run timename = new type[size];The array (element) data typeThe new operatorThe array(variable) nameThe assignment operatorThe number of elements0 12 3Instantiating ArraysExamples// instantiate an array of counterscounter = new int[5];// instantiate the array of gradesnumStudents = 10;grade = new double[numStudents];counter012340 <= index < size0 12 3Declaration and Instantiationtype[] name = new type[size];DeclarationInstantiation0 12 3Exampleint[] num = new int[5];0 12 3Array AccessExamplesaverageScore = (score[0]+score[1]+score[2])/3;numStudents = 3;totalScore = 0;for (int i = 0; i < numStudents; i++) { totalScore += score[i];}averageScore = totalScore/numStudents;double score[] = new score[3];score[0] = 98.3;score[1] = 57.8;score[2] = 93.4;often use loops for access0 12 3Array LengthArrays have length–an internal variable called length–number of elements in array–access the length variable using the “dot’ notation (arrayname.length)// loop through the array of test scoressumOfScores = 0;for (int i=0; i<scores.length; i++) { sumOfScores += scores[i];}0 12 3int counter[] = {0, 0, 0, 0, 0};char[] characterSet = {‘a’,’b’,’c’}; // etc.Initializing Arrays•Array elements are variables too!–if you don’t initialize, the contents are undefined•When and how?–if you don’t yet know the size•initialize at run time, typically with a loop–if you know how many elements•perhaps use an initializer list0 12 3•List the initial value for the elements of an array•Items are separated by commas and the list is in braces {}•The size of the array is determined by the number of items in the listint[] scores = {87, 98, 45};•Can only be used in the same statement as declaring the arrayNOT int[] scores;scores = {87, 98, 45};Initializer Lists0 12 3Array Bounds•Arrays have finite size•If you access an element outside of the array, you’ll get an ArrayIndexOutOfBounds ExceptionExample:int grades[] = {99, 98, 95, 96};System.out.println (grades[4]);0 12 3int arraySize;System.out.print ("Enter the size of the array:"); arraySize = Integer.parseInt(keyboard.readLine());int[] list = new int[arraySize];Specify Array Size During Program ExecutionExample0 12 3(Assume that keyboard has already been declared and instantiated.)Examplefor (int ind = 0; ind < sale.length; ind++){ sale[ind] = 10.00;}Initialize Array to Specific Value (10.00)(Assume that sale has already been declared and instantiated.)0 12 3Examplefor (int ind = 0; ind < sale.length; ind++){ sale[ind] = Double.parseDouble(keyboard.readLine());}(Assume that sale has already been declared and instantiated, and that keyboard has already been declared and instantiated.)Read Data into Array0 12 3Examplefor (int ind = 0; ind < sale.length; ind++){ System.out.print(sale[ind] + " ");}Print Array(Assume that sale has already been declared and instantiated.)0 12 3Parallel ArraysArrays are parallel if corresponding components hold related informationString[] studentName;double[] studentGPA;For example, studentName and studentGPA are parallel if studentGPA[3] is the GPA of the student with studentName[3].0 12 3In-Class Exercises1. Declare an array of integers called numbers2. Declare and instantiate an array of 26 characters called alphabet0 12 3In-Class Exercises3. Declare an array of 5 characters called grades and initialize it with the letters: A, B, C, D, FHint: type[] name = {initialization list};4. Write a loop to print the contents of an array named zipCodesHint: to access array element name[index]0 12 3In-Class Exercises5. Write a loop to change all the values of the integer array numbers to index + 10 12 3Exercises1. Find Sum and Average of Array2. Determine Largest and SmallestElements in Array0 12 3Homework 6 (practice)•Read data from file•Fill arrays with data•Fill objects with dataTomorrow•More Arrays–arrays of objects–passing arrays as parameters–searching and sorting•Homework 5 due Wednesday midnight•Homework 6 assigned•Bring
View Full Document