With sobs and tears he sorted outThose of the largest size . . . —Lewis Carroll Attempt the end, and never stand to doubt;Nothing’s so hard, but search will find it out. —Robert Herrick Now go, write it before them in a table,and note it in a book. —Isaiah 30:8 ’Tis in my memory lock’d,And you yourself shall keep the key of it. —William Shakespeare
OBJECTIVES In this chapter you will learn: • To use arrays to store lists and tables of values. • To declare an array, initialize an array and refer to individual elements of an array. • To pass arrays to functions. • To search and sort an array. • To declare and manipulate multidimensional arrays.
10.1 Introduction 10.2 Arrays 10.3 Declaring and Allocating Arrays 10.4 Examples Using Arrays 10.5 Random Image Generator Using Arrays 10.6 References and Reference Parameters 10.7 Passing Arrays to Functions 10.8 Sorting Arrays 10.9 Searching Arrays: Linear Search and Binary Search 10.10 Multidimensional Arrays 10.11 Building an Online Quiz 10.12 Wrap-Up 10.13 Web Resources
Common Programming Error 10.1 It is important to note the difference between the “seventh element of the array” and “array element seven.” Because array subscripts begin at 0, the seventh element of the array has a subscript of 6, while array element seven has a subscript of 7 and is actually the eighth element of the array. This confusion is a source of “off-by-one” errors.
Fig. 10.2 | Precedence and associativity of the operators discussed so far.
Common Programming Error 10.2 Assuming that the elements of an array are initialized when the array is allocated may result in logic errors.
Fig. 10.3 | Initializing the elements of an array (Part 1 of 3). Operator new allocates an Array called n1 with five elements Operator new allocates an empty Array called n2 Zero-based counting used in for loop to set each element’s value equal to its subscript Five elements added and initialized in n2, which dynamically expands
Fig. 10.3 | Initializing the elements of an array (Part 2 of 3). Outputs the subscript and value of every array element in a table
Common Programming Error 10.3 Referring to an element outside the Array bounds is normally a logic error.
Error-Prevention Tip 10.1 When using subscripts to loop through an Array, the subscript should never go below 0 and should always be less than the number of elements in the Array (i.e., one less than the size of the Array ). Make sure that the loop-terminating condition prevents the access of elements outside this range.
10.4 Examples Using Arrays (Cont.) • Arrays can be created using a comma-separated initializer list enclosed in square brackets () • The array’s size is determined by the number of values in the initializer list • The initial values of an array can be specified as arguments in the parentheses following new Array • The size of the array is determined by the number of values in parentheses
Fig. 10.4 | Declaring and initializing arrays (Part 1 of 3). Creates an array with four elements, all of which are defined Creates an array with four elements, all of which are defined in an initializer list Creates an array with four elements, two of which reserve space for values to be specified later
10.4 Examples Using Arrays (Cont.) • for…in statement • Enables a script to perform a task for each element in an array • Process is known as iterating over the elements of an array
Error-Prevention Tip 10.2 When iterating over all the elements of an Array, use a for…in statement to ensure that you manipulate only the existing elements of the Array. Note that a for…in statement skips any undefined elements in the array.
Fig. 10.6 | Dice-rolling program using an array instead of a switch(Part 1 of 2). Creates a frequency array with each element’s index corresponding to a face value (we leave index 0 uninitialized because the lowest face value is 1) Randomly picks a face of the die and increments the value of the element with the corresponding index in the frequency array
Fig. 10.6 | Dice-rolling program using an array instead of a switch(Part 2 of 2). Outputs results in a table
10.5 Random Image Generator Using Arrays • Random image generator • Uses a pictures array to store the names of the image files as strings • Accesses the array using a randomized index
Fig. 10.7 | Random image generation using arrays (Part 1 of 2). Creates an array with the names of the images to choose from Randomly selects an element from the array and appends its value to “.gif\” to create the src attribute’s value
Error-Prevention Tip 10.3 With pass-by-value, changes to the copy of the called function do not affect the original variable’s value in the calling function. This prevents the accidental side effects that so greatly hinder the development of correct and reliable software systems.
Software Engineering Observation 10.3 When returning information from a function via a return statement, numbers and boolean values are always returned by value (i.e., a copy is returned), and objects are always returned by reference (i.e., a reference to the object is returned). Note that, in the pass-by-reference case, it is not necessary to return the new value, since the object is already modified.
10.7 Passing Arrays to Functions • Pass an array as an argument to a function • Specify the name of the array (a reference to the array) without brackets • Although entire arrays are passed by reference, individual numeric and boolean array elements are passed by value exactly as simple numeric and boolean variables are passed • Such simple single pieces of data are called scalars, or scalar quantities • To pass an array element to a function, use the subscripted name of the element as an argument in the function call • join method of an Array • Returns a string that contains all of the elements of an array, separated by the string supplied in the function’s argument • If an argument is not specified, the empty string is used as the separator
Fig. 10.8 | Passing arrays and individual array elements to functions (Part 1 of 3). Passes array a to function modifyArray by reference Passes array element a to function modifyElement by value
Fig. 10.8 | Passing arrays and individual array elements to functions (Part 2 of 3). Creates a string containing all the elements in theArray, separated by “ ” Multiplies each element in theArray by 2, which persists after the function has finished Multiplies the array element by 2, but only for the duration of the function
Fig. 10.8 | Passing arrays and individual array elements to functions (Part 3 of 3).
Fig. 10.9 | Sorting an array with sort (Part 1 of 2). Passes function compareIntegers to method a.sort to arrange the elements of a in ascending numerical order
Defines a function comparing integers to be passed to method sort (to replace the default string comparison function) Fig. 10.9 | Sorting an array with sort (Part 2 of 2).
10.9 Searching Arrays: Linear Search and Binary Search • Linear search algorithm • Iterates through the elements of an array until it finds an element that matches a search key, and returns the subscript of the element • If the key is not found, the function returns -1 • If the array being searched is not in any particular order, it is just as likely that the value will be found in the first element as the last • On average, the program will have to compare the search key with half the elements of the array
Fig. 10.10 | Linear search of an array (Part 1 of 3). Creates a new array to search Initializes each array element with a value double its index
Fig. 10.10 | Linear search of an array (Part 2 of 3). Calls function linearSearch on array a with the value input by the user Iterates through every element of the array until the key is found If the key is encountered, the index of the element with the key as its value is returned If the key is not found, -1 is returned
Fig. 10.10 | Linear search of an array (Part 3 of 3). When the Search button is pressed, calls function buttonPressed