Outline. 7.1 Introduction. 7.2 Arrays. 7.2 Arrays

Size: px
Start display at page:

Download "Outline. 7.1 Introduction. 7.2 Arrays. 7.2 Arrays"

Transcription

1 jhtp5_07.fm Page 279 Wednesday, November 20, :44 PM 7 Arrays Objectives To introduce the array data structure. To understand the use of arrays to store, sort and search lists and tables of values. To understand how to declare an array, initialize an array and refer to individual elements of an array. To be able to pass arrays to methods. To be able to declare and manipulate multidimensional arrays. With sobs and tears he sorted out Those 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

2 280 Arrays Chapter 7 Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Creating Arrays 7.4 Examples Using Arrays 7.5 References and Reference Parameters 7.6 Passing Arrays to Methods 7.7 Sorting Arrays 7.8 Searching Arrays: Linear Search and Binary Search 7.9 Multidimensional Arrays 7.10 (Optional Case Study) Thinking About Objects: Collaboration Among Objects Summary Terminology Self-Review Exercises Answers to Self-Review Exercises Exercises Recursion Exercises Special Section: Building Your Own Computer 7.1 Introduction This chapter introduces the important topic of data structures collections of related data items. Arrays are data structures consisting of related data items of the same type. Arrays are fixed-length entities they remain the same length once they are created, although an array reference may be reassigned to a new array of a different length. Chapter 20, Data Structures, introduces dynamic data structures, such as lists, queues, stacks and trees, that can grow and shrink as programs execute. Chapter 21, Java Utilities Package and Bit Manipulation, discusses class Vector, which is an array-like class whose objects can grow and shrink in response to a Java program s changing storage requirements. Chapter 22, Collections, introduces Java s predefined data structures that enable the programmer to use existing data structures for lists, queues, stacks and trees. The Collections API also provides class Arrays, which provides a set of utility methods for array manipulation. 7.2 Arrays In Java, an array is a group of variables (called elements or components) containing values that all have the same type. Recall from Section 3.5 that types in Java are divided into two categories primitive types and reference types. Java arrays are objects, so they are considered reference types. The elements of a Java array can be either primitive types or reference types (including arrays, as we will see in Section 7.9). To refer to a particular element in an array, we specify the name of the reference to the array and the position number of the element in the array. The position number of the element is formally called the element s index or subscript. Figure 7.1 presents a logical representation of an integer array called c. This array contains 12 elements (i.e., variables). A program refers to any one of these elements with an array-access expression that includes the name of the array followed by the index of the particular element in square brackets ( []). The first element in every array has index zero

3 Chapter 7 Arrays 281 Name of array (note that all elements of this array have the same name, c ) Index (or subscript) of the element in array c c[ 0 ] c[ 1 ] c[ 2 ] c[ 3 ] c[ 4 ] c[ 5 ] c[ 6 ] c[ 7 ] c[ 8 ] c[ 9 ] c[ 10 ] c[ 11 ] Fig. 7.1 A 12-element array. (sometimes called the zeroth element). Thus, the first element of array c is c[ 0], the second element of array c is c[ 1], the seventh element of array c is c[ 6] and, in general, the i th element of array c is c[ i-1]. Array names follow the same conventions as do other variable names. An index must be a positive integer or an integer expression that can be promoted to an int. If a program uses an expression as an index, the program evaluates the expression to determine the index. For example, if we assume that variable a is 5 and that variable b is 6, then the statement c[ a + b ] += 2 ; adds 2 to array element c[ 11 ]. Note that an indexed array name is an array-access expression. Such expressions can be used on the left side of an assignment to place a new value into an array element. Common Programming Error 7.1 Using a value of type long as an array index results in a compilation error. 7.1 Let us examine array c in Fig. 7.1 more closely. The name of the reference to the array is c. Every array object in Java knows its own length and maintains this information in a field of the array object called length. The expression c.length accesses array c s length field to determine the length of the array. This array s 12 elements are referred to as c[ 0], c[ 1], c[ 2],, c[ 11 ]. The value of c[ 0] is -45, the value of c[ 1] is 6, the value of c[ 2] is 0, the value of c[ 7] is 62 and the value of c[ 11 ] is 78. To calculate the sum

4 282 Arrays Chapter 7 of the values contained in the first three elements of array c and store the result in variable sum, we would write sum = c[ 0 ] + c[ 1 ] + c[ 2 ]; To divide the value of the seventh element of array c by 2 and assign the result to the variable x, we would write x = c[ 6 ] / 2 ; Common Programming Error 7.2 Note the difference between the seventh element of the array and array element seven. Array indices begin at 0, so the seventh element of the array has an index of 6, while array element seven has an index of 7 and is actually the eighth element of the array. This confusion is a source of off-by-one errors Declaring and Creating Arrays Array objects occupy space in memory. All objects in Java (including arrays) must be created with keyword new (as discussed in Section 4.9). For an array, the programmer specifies the type of the array elements and the number of elements as part of an array-creation expression that uses keyword new. The following declaration and array-creation expression create 12 elements for the integer array c in Fig. 7.1: int c[] = new int [ 12 ]; This task also can be performed in two steps as follows: int c[]; // declares the array variable c = new int [ 12 ]; // creates the array When creating an array, each element of the array receives a default value zero for the numeric primitive-type elements, false for boolean elements and null for references (any nonprimitive type). Common Programming Error 7.3 Unlike array declarations in several other programming languages (such as C and C++), Java array declarations do not specify the number of array elements in the square brackets after the array name (e.g., int c[ 12 ] ; ); otherwise, a syntax error occurs. 7.3 A program can create several arrays in a single declaration. The following String array declaration reserves 100 elements for b and 27 elements for x : String b[] = new String[ 100 ], x[] = new String[ 27 ]; When declaring an array, the type of the array and the square brackets can be combined at the beginning of the declaration to indicate that all identifiers in the declaration are array references. For example, double[] array1, array2; declares array1 and array2 as references to arrays of double values. As shown previously, the declaration and creation of the array can be combined in the declaration. The following declaration reserves 10 elements for array1 and 20 elements for array2:

5 Chapter 7 Arrays 283 double[] array1 = new double[ 10 ], array2 = new double[ 20 ]; A program can declare arrays of any type. Every element of a primitive-type array contains is a variable of the array s declared type. For example, every element of an int array is an int variable. In an array of a reference type, every element of the array is a reference to an object of the array s declared type. For example, every element of a String array is a reference to a String object. 7.4 Examples Using Arrays This section presents several examples that demonstrate declaring arrays, creating arrays, initializing arrays and manipulating array elements. For simplicity, the examples in this section use arrays that contain elements of type int. Please remember that programs can create arrays of any type. Creating and Initializing an Array The application of Fig. 7.2 uses keyword new to create an array of 10 int elements, which are initially zero (the default for int variables). The program displays the array elements in tabular format in an object of class JTextArea. 1 // Fig. 7.2: InitArray.java 2 // Creating an array. 3 import javax.swing.*; 4 5 public class InitArray { 6 7 public static void main( String args[] ) 8 { 9 10 int array[]; // declare reference to an array 11 array = new int [ 10 ]; // create array String output = "Index\tValue\n"; // append each array element's value to String output for ( int counter = 0 ; counter < array.length; counter++ ) output += counter + "\t" + array[ counter ] + "\n"; JTextArea outputarea = new JTextArea(); 20 outputarea.settext( output ); JOptionPane.showMessageDialog( null, outputarea, 23 "Initializing an Array of int Values", 24 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } // end main } // end class InitArray Fig. 7.2 Initializing the elements of an array to zero. (Part 1 of 2.)

6 284 Arrays Chapter 7 Fig. 7.2 Initializing the elements of an array to zero. (Part 2 of 2.) Line 9 declares array a reference capable of referring to an array of int elements. Line 11 creates the array and assigns a reference to the resulting array object to reference array. The program builds its output in the String called output that will be displayed in a JTextArea on a message dialog. Line 13 assigns output the headings for the columns displayed by the program. The first column represents the index for each array element, and the second column represents the value of each array element. Lines use a for statement to append the index number (represented by counter ) and value of each array element (represented by array[ counter ] ) to output. Note that the loop uses zero-based counting (remember, index values start at 0), so that the loop can access every array element. Also, in the for s condition, note the use of the expression array.length to determine the length of the array. In this example, the length of the array is 10, so the loop continues executing as long as the value of control variable counter is less than 10. For a 10-element array, the index values are 0 through 9, so using the less-than operator guarantees that the loop does not attempt to access an element beyond the end of the array. Using an Array Initializer As an alternative to an array-creation expression, a program can create an array and initialize its elements with an array initializer, which is a comma-separated list of expressions (sometimes called an initializer list) enclosed in braces ( { and } ). In this case, the array length is determined by the number of elements in the initializer list. For example, the declaration int n[] = { 10, 20, 30, 40, 50 }; creates a five-element array with index values 0, 1, 2, 3 and 4. This declaration does not require new to create the array object. When the compiler encounters an array declaration that includes an initializer list, the compiler counts the number of initializers in the list to determine the appropriate number of array elements. The application of Fig. 7.3 initializes an integer array with 10 values (line 11) and displays the array in tabular format in a JTextArea on a message dialog. The code for displaying the array elements (lines 13 24) is identical to that of Fig. 7.2.

7 Chapter 7 Arrays // Fig. 7.3: InitArray.java 2 // Initializing an array with a declaration. 3 import javax.swing.*; 4 5 public class InitArray { 6 7 public static void main( String args[] ) 8 { // array initializer specifies number of elements and // value for each element int array[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; 13 String output = "Index\tValue\n"; // append each array element's value to String output 16 for ( int counter = 0 ; counter < array.length; counter++ ) 17 output += counter + "\t" + array[ counter ] + "\n"; JTextArea outputarea = new JTextArea(); 20 outputarea.settext( output ); JOptionPane.showMessageDialog( null, outputarea, 23 "Initializing an Array with a Declaration", 24 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } // end main } // end class InitArray Fig. 7.3 Initializing the elements of an array with a declaration. Calculating the Value to Store in Each Array Element Some programs calculate the value stored in each array element. The application of Fig. 7.4 creates a 10-element array and assigns each element on of the even integers from 2 to 20 ( 2, 4, 6,, 20). Then the program displays the array in tabular format. The for statement at lines generates an array element s value by multiplying the current value of the for loop s control variable counter by 2 and adding 2.

8 286 Arrays Chapter 7 1 // Fig. 7.4: InitArray.java 2 // Initialize array with the even integers from 2 to import javax.swing.*; 4 5 public class InitArray { 6 7 public static void main( String args[] ) 8 { final int ARRAY_LENGTH = 10 ; int array[]; // constant // reference to int array 12 array = new int [ ARRAY_LENGTH ]; // create array // calculate value for each array element 15 for ( int counter = 0 ; counter < array.length; counter++ ) 16 array[ counter ] = * counter; String output = "Index\tValue\n"; for ( int counter = 0 ; counter < array.length; counter++ ) 21 output += counter + "\t" + array[ counter ] + "\n"; JTextArea outputarea = new JTextArea(); 24 outputarea.settext( output ); JOptionPane.showMessageDialog( null, outputarea, 27 "Initializing to Even Numbers from 2 to 20", 28 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } // end main } // end class InitArray Fig. 7.4 Generating values to be placed into elements of an array. Line 9 uses the final qualifier to declare constant ARRAY_LENGTH, whose value is 10. Recall from Section 6.8 that constants must be initialized before they are used and

9 Chapter 7 Arrays 287 cannot be modified thereafter. If an attempt is made to modify a final variable after it is declared as shown on line 11, the compiler issues a message like cannot assign a value to final variable variablename If an attempt is made to use a final variable before it is initialized, the compiler issues the error message Variable variablename may not have been initialized Constants also are called named constants or read-only variables. Such variables often can make programs more readable. Common Programming Error 7.4 Assigning a value to a constant after the variable has been initialized results in a compilation error. 7.4 Summing the Elements of an Array Often, the elements of an array represent a series of values to be used in a calculation. For example, if the elements of an array represent the grades for an exam, the professor may wish to total the elements of the array and use that sum to calculate the class average for the exam. The application of Fig. 7.5 sums the values contained in the 10-element integer array. The program declares, creates and initializes the array at line 9. The for statement at lines performs the calculations. [ Note: The values supplied as array initializers normally are read into a program, rather than specified in an initializer list. For example, an applet user could enter the values through a JTextField, or, in an application, the values could be read from a file on disk (as discussed in Chapter 17). Reading the data into a program makes the program more flexible, because it can be used with different sets of data.] 1 // Fig. 7.5: SumArray.java 2 // Total the values of the elements of an array. 3 import javax.swing.*; 4 5 public class SumArray { 6 7 public static void main( String args[] ) 8 { 9 int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 10 int total = 0 ; // add each element's value to total for ( int counter = 0 ; counter < array.length; counter++ ) total += array[ counter ]; 16 JOptionPane.showMessageDialog( null, 17 "Total of array elements: " + total, 18 "Sum the Elements of an Array", 19 JOptionPane.INFORMATION_MESSAGE ); 20 Fig. 7.5 Computing the sum of the elements of an array. (Part 1 of 2.)

10 288 Arrays Chapter 7 21 System.exit( 0 ); } // end main } // end class SumArray Fig. 7.5 Computing the sum of the elements of an array. (Part 2 of 2.) Using Histograms to Display Array Data Graphically Many programs present data to users in a graphical manner. For example, numeric values are often displayed as bars in a bar chart, or histogram. In such a chart, longer bars represent larger numeric values. One simple way to display numeric data graphically is with a histogram that shows each numeric value as a bar of asterisks ( * ). Our next application (Fig. 7.6) reads numbers from an array and graphs the information in the form of a histogram. The program displays each value followed by a bar consisting of that many asterisks. The nested for statements (lines 14 21) append the bars to the string output that will be displayed in textarea outputarea on a message dialog. Note the condition of the for statement at line 18 (stars <array[ counter ] ). Each time the program reaches that inner for statement (lines 18 19), the loop counts from 0 up to array[counter], thus using a value in array to determine the final value of the control variable stars and the number of asterisks to display. 1 // Fig. 7.6: Histogram.java 2 // Histogram printing program. 3 import javax.swing.*; 4 5 public class Histogram { 6 7 public static void main( String args[] ) 8 { 9 int array[] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; String output = "Element\tValue\tHistogram"; // for each array element, output a bar in histogram 14 for ( int counter = 0 ; counter < array.length; counter++ ) { } // end outer for output += "\n" + counter + "\t" + array[ counter ] + "\t" ; // print bar of asterisks for ( int stars = 0 ; stars < array[ counter ]; stars++ ) output += "*" ; Fig. 7.6 A program that prints histograms. (Part 1 of 2.)

11 Chapter 7 Arrays JTextArea outputarea = new JTextArea(); 24 outputarea.settext( output ); JOptionPane.showMessageDialog( null, outputarea, 27 "Histogram Printing Program", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } // end main } // end class Histogram Fig. 7.6 A program that prints histograms. (Part 2 of 2.) Using the Elements of an Array as Counters Sometimes, programs use a series of counter variables to summarize data, such as the results of a survey. In Fig. 6.8, we used a series of counters in our die-rolling program to track the number of occurrences of each side on a six-sided die as the program rolled the die 6000 times. We also indicated that there is a more elegant technique for summarizing the die values. An array version of the application in Fig. 6.8 is shown in Fig // Fig. 7.7: RollDie.java 2 // Roll a six-sided die 6000 times. 3 import javax.swing.*; 4 5 public class RollDie { 6 7 public static void main( String args[] ) 8 { 9 int frequency[] = new int [ 7 ]; // roll die 6000 times; use die value as frequency index 12 for ( int roll = 1 ; roll <= 6000; roll++ ) frequency[ 1 + ( int ) ( Math.random() * 6 ) ]; String output = "Face\tFrequency"; 16 Fig. 7.7 Die-rolling program using arrays instead of switch. (Part 1 of 2.)

12 290 Arrays Chapter 7 17 // append frequencies to String output 18 for ( int face = 1 ; face < frequency.length; face++ ) 19 output += "\n" + face + "\t" + frequency[ face ]; JTextArea outputarea = new JTextArea(); 22 outputarea.settext( output ); JOptionPane.showMessageDialog( null, outputarea, 25 "Rolling a Die 6000 Times", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } // end main } // end class RollDie Fig. 7.7 Die-rolling program using arrays instead of switch. (Part 2 of 2.) The program uses the seven-element array frequency (line 9) to count the occurrences of each side of the die. Line 13 of this program replaces lines of Fig Line 13 uses the random value as the index for array frequency to determine which element the program should increment during each iteration of the loop. The random-number calculation on line 13 produces numbers from 1 to 6 (the values for a six-sided die), so the frequency array must be large enough to store six counters. However, in this program, we chose to use a seven-element array. We ignore the first array element, frequency[ 0], because it is more logical to have the face value 1 increment frequency[ 1] than frequency[ 0]. This allows us to use each face value directly as an index for array frequency. Good Programming Practice 7.1 Strive for program clarity. It is sometimes worthwhile to trade off the most efficient use of memory or processor time in favor of writing clearer programs. 7.1 Also, lines of this program replace lines from Fig We can loop through array frequency, so we do not have to enumerate each line of text to display in the JTextArea as we did in Fig Using Arrays to Analyze Survey Results Our next example uses arrays to summarize the results of data collected in a survey. Consider the following problem: Forty students were asked to rate the quality of the food in the student cafeteria on a scale of 1 to 10 (where 1 means awful and 10 means excellent). Place the 40 responses in an integer array, and summarize the results of the poll.

13 Chapter 7 Arrays 291 The solution to this problem is a typical array-processing application (see Fig. 7.8). We wish to summarize the number of responses of each type (i.e., 1 through 10). The array responses is a 40-element integer array of the students responses to the survey. We use an 11-element array frequency to count the number of occurrences of each response. As in Fig. 7.7, we ignore the first element ( frequency[ 0] ), because it is more logical to have the response 1 increment frequency[ 1] than frequency[ 0]. This allows us to use each response directly as the frequency array index. Each element of the array is used as a counter for one of the survey responses. The for loop at lines takes the responses one at a time from array responses and increments one of the 10 counters in the frequency array ( frequency[ 1] to frequency[ 10 ] ). The key statement in the loop is line 17, which increments the appropriate frequency counter, depending on the value of responses[ answer ]. 1 // Fig. 7.8: StudentPoll.java 2 // Student poll program. 3 import javax.swing.*; 4 5 public class StudentPoll { 6 7 public static void main( String args[] ) 8 { 9 int responses[] = { 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6, 10 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6, 11 4, 8, 6, 8, 10 }; // for each answer, select responses element and use that value 15 // as frequency index to determine element to increment 16 for ( int answer = 0 ; answer < responses.length; answer++ ) int frequency[] = new int [ 11 ]; ++frequency[ responses[ answer ] ]; 19 String output = "Rating\tFrequency\n"; // append frequencies to String output 22 for ( int rating = 1 ; rating < frequency.length; rating++ ) 23 output += rating + "\t" + frequency[ rating ] + "\n"; JTextArea outputarea = new JTextArea(); 26 outputarea.settext( output ); JOptionPane.showMessageDialog( null, outputarea, 29 "Student Poll Program", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } // end main } // end class StudentPoll Fig. 7.8 A simple student-poll analysis program. (Part 1 of 2.)

14 292 Arrays Chapter 7 Fig. 7.8 A simple student-poll analysis program. (Part 2 of 2.) Let s consider several iterations of the for loop. When control variable answer is 0, the value of responses[ answer ] is the value of the first element of array responses (i.e., 1 ), so the program interprets ++frequency[ responses[ answer ]]; as ++frequency[ 1 ]; which increments the value in array element one. To evaluate the expression, start with the value in the innermost set of square brackets (answer ). Once you know answer s value, plug that value into the expression and evaluate the next outer set of square brackets (i.e., responses[answer] ). Then, use the resulting value as the index for the frequency array to determine which counter to increment. When answer is 1, responses[ answer ] is the value of responses s second element ( 2 ), so the program interprets ++frequency[ responses[ answer ]]; as ++frequency[ 2 ]; which increments array element two (the third element of the array). When answer is 2, responses[ answer ] is the value of responses s third element ( 6 ), so the program interprets ++frequency[ responses[ answer ]]; as ++frequency[ 6 ]; which increments array element six (the seventh element of the array), and so on. Regardless of the number of responses processed in the survey, the program requires only an 11- element array (ignoring element zero) to summarize the results, because all the response values are between 1 and 10 and the index values for an 11-element array are 0 through 10. Also, note that the summarized results are correct, because the elements of array frequency were initialized to zero when the array was created with new. If the data had contained invalid values, such as 13, the program would have attempted to add 1 to frequency[13]. This element is outside the bounds of the array. In the C and C++ programming languages, such a reference would be allowed by the compiler and at execution time. The program would walk past the end of the array to where element number 13 would have been located had it existed and add 1 to whatever happens to be at that location in memory. This operation could potentially modify another variable in the

15 Chapter 7 Arrays 293 program or even result in premature program termination. Java prevents accessing elements outside the array bounds. Error-Prevention Tip 7.1 When a Java program executes, the Java interpreter checks array indices to ensure that they are valid (i.e., all array indices must be greater than or equal to 0 and less than the length of the array). If there is an invalid index, Java generates an exception. 7.1 Error-Prevention Tip 7.2 Exceptions indicate that an error occurred in a program. A programmer can write code to recover from an exception and continue program execution, rather than abnormally terminating the program. When a program attempts to access an element outside the array bounds, Java generates an ArrayIndexOutOfBoundsException Error-Prevention Tip 7.3 When looping through an array, the array index should never go below 0 and should always be less than the length of the array. The loop-terminating condition should prevent the accessing of elements outside this range References and Reference Parameters Section 7.5 demonstrates how to pass arrays and array elements as arguments to methods. First, we introduce the mechanisms used to pass arguments to methods. Two ways to pass arguments to methods in many programming languages (like C and C++) are pass-by-value and pass-by-reference (also called call-by-value and call-by-reference ). When an argument is passed by value, a copy of the argument s value is made and passed to the called method. Error-Prevention Tip 7.4 With pass-by-value, changes to the called method s copy do not affect the original variable s value in the caller. This prevents the accidental side effects that greatly hinder the development of correct and reliable software systems. 7.4 When an argument is passed by reference, the caller gives the called method the ability to access the caller s data directly and possibly modify that data. Pass-by-reference also improves performance by eliminating the overhead of copying large amounts of data. Software Engineering Observation 7.1 Unlike other languages, Java does not allow the programmer to choose whether to pass each argument by value or by reference. Primitive-type variables are always passed by value. Objects are not passed to methods; rather, references to objects are passed. The references themselves are passed by value that is, a copy of a reference is passed to a method. With a reference to an object, the method can manipulate the object directly. 7.1 Software Engineering Observation 7.2 When returning information from a method via a return statement, primitive types 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) Exception handling is discussed in Chapter 15.

16 294 Arrays Chapter 7 To pass a reference to an object to a method, simply specify the reference name in the method call. The corresponding method-parameter name actually refers to the original object in memory, and the original object can thus be accessed directly in the called method. Recall from Section 7.2 that arrays are objects in Java; therefore, arrays are passed to methods by reference a called method can access the elements of the caller s original arrays. The name of an array variable is actually a reference to an object that contains the array elements and the length field, a constant that indicates the number of elements in the array. In the next section, we demonstrate pass-by-value and pass-by-reference as used with arrays. Performance Tip 7.1 Passing arrays by reference makes sense for performance reasons. If arrays were passed by value, a copy of each element would be passed. For large, frequently passed arrays, this would waste time and would consume a considerable amount of storage for the copies of the arrays Passing Arrays to Methods To pass an array argument to a method, specify the name of the array without any brackets. For example, if array hourlytemperatures is declared as int hourlytemperatures[] = new int [ 24 ]; then the method call modifyarray( hourlytemperatures ); passes a reference to array hourlytemperatures to method modifyarray. In Java, every array object knows its own length (via the length field). Thus, when we pass an array object into a method, we are not required to pass the length of the array as an additional argument. Although entire arrays and objects referred to by individual elements of reference-type arrays are passed by reference, individual array elements of primitive types are passed by value exactly as simple variables are. Such primitive values are called scalars or scalar quantities. To pass an array element to a method, use the indexed name of the array as an argument in the method call. For a method to receive an array through a method call, the method s parameter list must specify an array parameter (or several if more than one array is to be received). For example, the method header for method modifyarray might be written as void modifyarray( int b[] ) indicating that modifyarray expects to receive an integer array in parameter b. Since arrays are passed by reference, when the called method uses the array name b, it refers to the actual array ( hourlytemperatures in the preceding call) in the calling method. The applet of Fig. 7.9 demonstrates the difference between passing an entire array and passing a primitive-type array element. Once again, we use an applet here because we have not yet defined an application that contains methods other than main. We are still taking advantage of some applet features, such as the automatic creation of an applet object and

17 Chapter 7 Arrays 295 the calls to init, start and paint by the applet container. In Chapter 9, Object-Oriented Programming, we will introduce applications that execute in their own windows. At that point, we will begin to see application classes that contain several methods. 1 // Fig. 7.9: PassArray.java 2 // Passing arrays and individual array elements to methods. 3 import java.awt.container; 4 import javax.swing.*; 5 6 public class PassArray extends JApplet { 7 8 // initialize applet 9 public void init() 10 { 11 JTextArea outputarea = new JTextArea(); 12 Container container = getcontentpane(); 13 container.add( outputarea ); int array[] = { 1, 2, 3, 4, 5 }; String output = "Effects of passing entire array by reference:\n" + 18 "The values of the original array are:\n"; // append original array elements to String output 21 for ( int counter = 0 ; counter < array.length; counter++ ) 22 output += " " + array[ counter ]; output += "\n\nthe values of the modified array are:\n"; // append modified array elements to String output 29 for ( int counter = 0 ; counter < array.length; counter++ ) 30 output += " " + array[ counter ]; output += "\n\neffects of passing array element by value:\n" + 33 "array[3] before modifyelement: " + array[ 3 ]; modifyelement( array[ 3 ] ); // attempt to modify array[ 3 ] output += "\narray[3] after modifyelement: " + array[ 3 ]; 38 outputarea.settext( output ); } // end method init modifyarray( array ); // array passed by reference // multiply each element of an array by 2 public void modifyarray( int array2[] ) { for ( int counter = 0 ; counter < array2.length; counter++ ) array2[ counter ] *= 2 ; } Fig. 7.9 Passing arrays and individual array elements to methods. (Part 1 of 2.)

18 296 Arrays Chapter 7 49 // multiply argument by 2 50 public void modifyelement( int element ) 51 { 52 element *= 2 ; 53 } } // end class PassArray Fig. 7.9 Passing arrays and individual array elements to methods. (Part 2 of 2.) Lines in method init create the JTextArea called outputarea and attach it to the applet s content pane. The for statement at lines appends the five elements of array (an array of int values) to the String called output. Line 24 invokes method modifyarray, passing array as an argument. Method modifyarray (lines 43 47) multiplies each element by two. To illustrate that array s elements were modified, the for statement at lines appends the five elements of array to output again. As the screen capture shows, method modifyarray did change the value of each element. Next, the program demonstrates that individual elements of primitive-type arrays are passed to methods by value. To show the value of array[ 3] before calling method modifyelement, lines append the value of array[ 3] (the fourth element with the value 8) to output. Line 35 invokes method modifyelement and passes array[ 3] as an argument. Remember that array[ 3] is actually one int value (8) in array. Also, remember that values of primitive types are passed to methods by value. Therefore, the program passes a copy of array[ 3]. Method modifyelement multiplies its argument by two and stores the result (16) in its parameter element. Method parameters, like local variables, cease to exist when the method in which they are declared completes execution. So, when method modifyelement terminates, the method parameter element is destroyed. Thus, when the program returns control to init, line 37 appends the unmodified value of array[ 3] (i.e., 8) to output. Line 38 displays the results in the JTextArea. 7.7 Sorting Arrays Sorting data (i.e., placing the data into some particular order, such as ascending or descending) is one of the most important computing applications. A bank sorts all checks by account number so that it can prepare individual bank statements at the end of each month. Telephone companies sort their lists of accounts by last name and, further, by first name to make it easy to find phone numbers. Virtually every organization must sort some data and, in many cases, massive amounts of data. Sorting data is an intriguing problem that has at-

19 Chapter 7 Arrays 297 tracted some of the most intense research efforts in the field of computer science. In this chapter, we discuss one of the simplest sorting schemes. In the exercises in this chapter, Chapter 20 and Chapter 22, we investigate more complex schemes that yield superior performance. Figure 7.10 sorts the values of array (a 10-element array of int variables) into ascending order. The technique we use is called the bubble sort or the sinking sort, because the smaller values gradually bubble their way to the top of the array (i.e., toward the first element) like air bubbles rising in water, while the larger values sink to the bottom (end) of the array. The technique uses nested loops to make several passes through the array. Each pass compares successive pairs of elements. If a pair is in increasing order (or the values are equal), the bubble sort leaves the values as they are. If a pair is in decreasing order, the bubble sort swaps their values in the array. The applet contains methods init, bubble- Sort and swap. Method init (lines 9 33) initializes the applet. Method bubblesort (lines 36 55) is called from init to sort the elements of array. Method bubblesort calls method swap (lines 58 65) as necessary to exchange two elements of the array. 1 // Fig. 7.10: BubbleSort.java 2 // Sort an array's values into ascending order. 3 import java.awt.*; 4 import javax.swing.*; 5 6 public class BubbleSort extends JApplet { 7 8 // initialize applet 9 public void init() 10 { 11 JTextArea outputarea = new JTextArea(); 12 Container container = getcontentpane(); 13 container.add( outputarea ); int array[] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; String output = "Data items in original order\n"; // append original array values to String output 20 for ( int counter = 0 ; counter < array.length; counter++ ) 21 output += " " + array[ counter ]; bubblesort( array ); // sort array 25 output += "\n\ndata items in ascending order\n"; // append sorted\ array values to String output 28 for ( int counter = 0 ; counter < array.length; counter++ ) 29 output += " " + array[ counter ]; outputarea.settext( output ); } // end method init 34 Fig Sorting an array with bubble sort. (Part 1 of 2.)

20 298 Arrays Chapter } // end method bubblesort } } // end class BubbleSort // sort elements of array with bubble sort public void bubblesort( int array2[] ) { // loop to control number of passes for ( int pass = 1 ; pass < array2.length; pass++ ) { // loop to control number of comparisons for ( int element = 0 ; element < array2.length - 1 ; element++ ) { // compare side-by-side elements and swap them if // first element is greater than second element if ( array2[ element ] > array2[ element + 1 ] ) swap( array2, element, element + 1 ); } // end loop to control comparisons } // end loop to control passes // swap two elements of an array public void swap( int array3[], int first, int second ) { int hold; // temporary holding area for swap hold = array3[ first ]; array3[ first ] = array3[ second ]; array3[ second ] = hold; Fig Sorting an array with bubble sort. (Part 2 of 2.) Lines append the original values of array to the String called output. Line 23 invokes method bubblesort and passes array as the array to sort. The method receives the array as parameter array2. The nested for statement at lines performs the sort. The outer loop controls the number of passes of the array. The inner loop controls the comparisons and swapping (if necessary) of the elements during each pass. Method bubblesort compares array2[ 0] to array2[ 1], then array2[ 1] to array2[ 2], then array2[ 2] to array2[ 3] and so on until it completes the pass by comparing array2[ 8] to array2[ 9]. Although there are 10 elements, the comparison loop per-

21 Chapter 7 Arrays 299 forms only nine comparisons. During each pass, a large value might move down the array (sink) many positions. However, a small value can move up (bubble) only one position per pass. On the first pass, the largest value is guaranteed to sink to the bottom element of the array, array2[ 9]. On the second pass, the second largest value is guaranteed to sink to array2[ 8]. On the ninth pass, the ninth largest value sinks to array2[ 1], leaving the smallest value in array2[ 0]. So, only nine passes are required to sort a 10-element array. If a comparison reveals that the two elements are in descending order, line 49 of bubblesort calls method swap to exchange the two elements so they will be in ascending order in the array. Method swap receives a reference to the array (which it calls array3) and two integers representing the indices of the two elements of the array to exchange. The exchange is performed by the three assignments in lines The extra variable hold temporarily stores one of the two values being swapped. The swap cannot be performed with only the two assignments array3[ first ] = array3[ second ]; array3[ second ] = array3[ first ]; If array3[ first ] is 7 and array3[ second ] is 5, after the first assignment both array elements contain 5 and the value 7 is lost hence, the extra variable hold is needed. The chief virtue of the bubble sort is that it is easy to program. However, the bubble sort runs slowly. This becomes apparent when sorting large arrays. In Exercise 7.11, we ask you to develop more efficient versions of the bubble sort. Other exercises investigate some sorting algorithms that are far more efficient than the bubble sort. 2 Performance Tip 7.2 Sometimes, the simplest algorithms perform poorly. Their virtue is that they are easy to program, test and debug. Sometimes, more complex algorithms are required to realize maximum performance Searching Arrays: Linear Search and Binary Search Often, programmers work with large amounts of data stored in arrays. It may be necessary to determine whether an array contains a value that matches a certain key value. The process of locating a key value in an array is called searching. In this section, we discuss two searching techniques the simple linear search and the more efficient binary search. 3 Searching an Array with Linear Search In the applet of Fig. 7.11, method linearsearch (declared at lines 47 58) uses a for statement (lines 50 54) containing an if statement to iterate over the elements of an array and compare each element with a search key the value to locate in the array. If the search key is found, the method returns the index of the element, thereby indicating the exact position of the search key in the array. If the search key is not found, the method returns the value 1. We return 1 because it is not a valid index. If the array being searched is not in any particular order, it is just as likely that the search key will be found in the first element 2. More advanced courses (often titled Data Structures, Algorithms or Computational Complexity ) investigate sorting and searching in greater depth. 3. Exercise 7.33 and Exercise 7.34 ask you to implement recursive versions of the linear search and the binary search, respectively.

22 300 Arrays Chapter 7 as the last. On average, therefore, the program will have to compare the search key with half the elements of the array. Figure 7.11 contains a 100-element array filled with the even integers from 0 to 198. The user types the search key in a JTextField and presses Enter to start the search. We pass a reference to the array to method linearsearch even though the array can be accessed in that method directly via the field array of class LinearSearch. We do this because a reference to an array normally is passed to a method of another class to search the corresponding array. For example, class Arrays (see Chapter 22) contains a variety of static methods for sorting arrays; searching arrays; comparing the contents of arrays; and filling arrays of primitive types, arrays of Object s and arrays of Strings. 1 // Fig. 7.11: LinearSearch.java 2 // Linear search of an array. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class LinearSearch extends JApplet implements ActionListener { 8 9 JLabel enterlabel, resultlabel; 10 JTextField enterfield, resultfield; 11 int array[]; // set up applet's GUI 14 public void init() 15 { 16 // get content pane and set its layout to FlowLayout 17 Container container = getcontentpane(); 18 container.setlayout( new FlowLayout() ); // set up JLabel and JTextField for user input 21 enterlabel = new JLabel( "Enter integer search key" ); 22 container.add( enterlabel ); enterfield = new JTextField( 10 ); 25 container.add( enterfield ); // register this applet as enterfield's action listener 28 enterfield.addactionlistener( this ); // set up JLabel and JTextField for displaying results 31 resultlabel = new JLabel( "Result" ); 32 container.add( resultlabel ); resultfield = new JTextField( 20 ); 35 resultfield.seteditable( false ); 36 container.add( resultfield ); // create array and populate with even integers 0 to array = new int [ 100 ]; 40 Fig Linear search of an array. (Part 1 of 2.)

23 Chapter 7 Arrays for ( int counter = 0 ; counter < array.length; counter++ ) 42 array[ counter ] = 2 * counter; } // end method init // search array for specified key value public int linearsearch( int array2[], int key ) { // loop through array elements for ( int counter = 0 ; counter < array2.length; counter++ ) // if array element equals key value, return location if ( array2[ counter ] == key ) return counter; return -1; // key not found } // end method linearsearch 60 // obtain user input and call method linearsearch 61 public void actionperformed( ActionEvent actionevent ) 62 { 63 // input also can be obtained with enterfield.gettext() 64 String searchkey = actionevent.getactioncommand(); // pass array reference to linearsearch; normally, a reference to an // array is passed to a method to search corresponding array object int element = linearsearch( array, Integer.parseInt( searchkey ) ); // display search result 71 if ( element!= -1 ) 72 resultfield.settext( "Found value in element " + element ); 73 else 74 resultfield.settext( "Value not found" ); } // method actionperformed } // end class LinearSearch Fig Linear search of an array. (Part 2 of 2.) Searching a Sorted Array with Binary Search The linear-search method works well for small arrays or for unsorted arrays. However, for large arrays, linear searching is inefficient. If the array is sorted, the high-speed binarysearch technique can be used.

24 302 Arrays Chapter 7 As we saw in the previous example, the linear-search algorithm compares the search key with an average of half the elements in the array. However, the binary-search algorithm eliminates half of the elements in the array being searched after each comparison. The algorithm locates the middle array element and compares it with the search key. If they are equal, the search key has been found, and the binary search returns the index of that element. Otherwise, the binary search reduces the problem to searching half of the sorted array. If the search key is less than the middle array element, the first half of the array will be searched; otherwise, the second half of the array will be searched. 4 If the search key is not the middle element in the specified subarray (i.e., part of the original array), the algorithm repeats on one quarter of the original array. The search continues until the search key is equal to the middle element of a subarray or until the subarray consists of one element that is not equal to the search key (i.e., the search key is not found). In the worst-case scenario, searching a sorted array of 1023 elements will take only 10 comparisons when using a binary search. Repeatedly dividing 1024 by 2 (because after each comparison, we are able to eliminate half of the array) yields the values 512, 256, 128, 64, 32, 16, 8, 4, 2 and 1. The number 1024 (2 10 ) is divided by 2 only 10 times to get the value 1. Dividing by 2 is equivalent to one comparison in the binary-search algorithm. Thus, an array of 1,048,576 (2 20 ) elements takes a maximum of 20 comparisons to find the key, and an array of one billion elements takes a maximum of 30 comparisons to find the key. This is a tremendous increase in performance over the linear search. For a one-billionelement array, this is a difference between an average of 500 million comparisons and a maximum of 30 comparisons! The maximum number of comparisons needed for the binary search of any sorted array is the exponent of the first power of 2 greater than the number of elements in the array. Figure 7.12 presents an iterative binarysearch method (lines ) that receives as arguments an integer array called array2 (the array to search) and an integer key (the search key). The program passes a reference to the array to method binarysearch. Once again, we do this because a reference to an array normally is passed to a method of another class to search the corresponding array. In binarysearch, if key matches the middle element of a subarray, binarysearch returns middle (the index of the current element) to indicate that the value was found and the search is complete. If key does not match the middle element of a subarray, binarysearch adjusts the low index or high index (both declared in the method), to continue the search, using a smaller subarray. If key is less than the middle element, the high index is set to middle -1, and the search continues on the elements from low to middle -1. If key is greater than the middle element, the low index is set to middle +1, and the search continues on the elements from middle +1 to high. The nested if else statement at lines performs these comparisons. 1 // Fig. 7.12: BinarySearch.java 2 // Binary search of an array. 3 import java.awt.*; 4 import java.awt.event.*; 5 import java.text.*; Fig Binary search of a sorted array. (Part 1 of 5.) 4. This example assumes that the array is sorted in ascending order.

25 Chapter 7 Arrays import javax.swing.*; 8 9 public class BinarySearch extends JApplet implements ActionListener { 10 JLabel enterlabel, resultlabel; 11 JTextField enterfield, resultfield; 12 JTextArea output; int array[]; 15 String display = ""; // set up applet's GUI 18 public void init() 19 { 20 // get content pane and set its layout to FlowLayout 21 Container container = getcontentpane(); 22 container.setlayout( new FlowLayout() ); // set up JLabel and JTextField for user input 25 enterlabel = new JLabel( "Enter integer search key" ); 26 container.add( enterlabel ); enterfield = new JTextField( 10 ); 29 container.add( enterfield ); // register this applet as enterfield's action listener 32 enterfield.addactionlistener( this ); // set up JLabel and JTextField for displaying results 35 resultlabel = new JLabel( "Result" ); 36 container.add( resultlabel ); resultfield = new JTextField( 20 ); 39 resultfield.seteditable( false ); 40 container.add( resultfield ); // set up JTextArea for displaying comparison data 43 output = new JTextArea( 6, 60 ); output.setfont( new Font( "Monospaced", Font. PLAIN, 12 ) ); container.add( output ); // create array and fill with even integers 0 to array = new int [ 15 ]; for ( int counter = 0 ; counter < array.length; counter++ ) 51 array[ counter ] = 2 * counter; } // end method init // obtain user input and call method binarysearch 56 public void actionperformed( ActionEvent actionevent ) 57 { Fig Binary search of a sorted array. (Part 2 of 5.)

26 304 Arrays Chapter 7 58 // input also can be obtained with enterfield.gettext() 59 String searchkey = actionevent.getactioncommand(); // initialize display string for new search 62 display = "Portions of array searched\n"; output.settext( display ); // display search result 70 if ( element!= -1 ) 71 resultfield.settext( "Found value in element " + element ); 72 else 73 resultfield.settext( "Value not found" ); } // end method actionperformed // perform binary search int element = binarysearch( array, Integer.parseInt( searchkey ) ); // method to perform binary search of an array public int binarysearch( int array2[], int key ) { int low = 0 ; // low element index int high = array2.length - 1 ; // high element index int middle; // middle element index // loop until low index is greater than high index while ( low <= high ) { middle = ( low + high ) / 2 ; // determine middle index // display subset of array elements used in this // iteration of binary search loop buildoutput( array2, low, middle, high ); // if key matches middle element, return middle location if ( key == array[ middle ] ) return middle; // if key less than middle element, set new high element else if ( key < array[ middle ] ) high = middle - 1 ; // key greater than middle element, set new low element else low = middle + 1 ; } // end while return -1; // key not found } // end method binarysearch Fig Binary search of a sorted array. (Part 3 of 5.)

27 Chapter 7 Arrays // build row of output showing subset of array elements 111 // currently being processed 112 void buildoutput( int array3[], int low, int middle, int high ) 113 { 114 // create 2-digit integer number format 115 DecimalFormat twodigits = new DecimalFormat( "00" ); // loop through array elements 118 for ( int counter = 0 ; counter < array3.length; counter++ ) { // if counter outside current array subset, append 121 // padding spaces to String display 122 if ( counter < low counter > high ) 123 display += " " ; // if middle element, append element to String display 126 // followed by asterisk (*) to indicate middle element 127 else if ( counter == middle ) 128 display += twodigits.format( array3[ counter ] ) + "* " ; else // append element to String display 131 display += twodigits.format( array3[ counter ] ) + " " ; } // end for display += "\n"; } // end method buildoutput } // end class BinarySearch Fig Binary search of a sorted array. (Part 4 of 5.)

28 306 Arrays Chapter 7 Fig Binary search of a sorted array. (Part 5 of 5.) This program uses a 15-element array. The first power of 2 greater than the number of elements is 16 (2 4 ), so binarysearch requires at most four comparisons to find the key. To illustrate this, line 90 calls method buildoutput (declared at lines ) to output each subarray during the binary-search process. Method buildoutput marks the middle element in each subarray with an asterisk ( * ) to indicate the element with which the key is compared. No matter what search key is entered, each search in this example results in a maximum of four lines of output one per comparison. Textarea output uses Monospaced font (a fixed-width font i.e., all characters are the same width) to help align the displayed text in each line of output. Line 44 uses method setfont to change the font displayed in output. Method setfont can change the font of text displayed on most GUI components. The method requires a Font (package java.awt) object as its argument. A Font object is initialized with three arguments the String name of the font ( "Monospaced"), an int representing the style of the font ( Font.PLAIN is a constant integer declared in class Font that indicates plain font) and an int representing the point size of the font (12 ). Java provides generic names for several fonts available on every Java platform. Monospaced font is also called Courier. Other common fonts include Serif (also called TimesRoman ) and SansSerif (also called Helvetica). Java provides access to all fonts on your system via methods of class Graphics- Environment (package java.awt). The style can also be Font.BOLD, Font.ITALIC or Font.BOLD +Font.ITALIC. The point size represents the size of the font. There are 72 points to an inch. The actual size of the text as it appears on the screen may vary based on the size of the screen and the screen resolution. 7.9 Multidimensional Arrays Multidimensional arrays with two dimensions are often used to represent tables of values consisting of information arranged in rows and columns. To identify a particular table element, we must specify two indices. By convention, the first identifies the element s row and the second identifies the element s column. Arrays that require two indices to identify a particular element are called two-dimensional arrays. (Multidimensional arrays can have more than two dimensions.) Java does not support multidimensional arrays directly, but does allow the programmer to specify one-dimensional arrays whose elements are also one-dimensional arrays, thus achieving the same effect. Figure 7.13 illustrates a two-dimensional array

29 Chapter 7 Arrays 307 Row 0 Row 1 Row 2 Column 0 Column 1 Column 2 Column 3 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ] a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ] a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ] Column index Row index Array name Fig Two-dimensional array with three rows and four columns. a that contains three rows and four columns (i.e., a three-by-four array). In general, an array with m rows and n columns is called an m-by-n array. Every element in array a is identified in Fig by an array-access expression of the form a[ row ][ column ] ; a is the name of the array reference, and row and column are the indices that uniquely identify each element in array a by row and column number. Notice that the names of the elements in the first row all have a first index of 0 ; the names of the elements in the fourth column all have a second index of 3. Arrays of One-Dimensional Arrays Like one-dimensional arrays, multidimensional arrays can be initialized with array initializers in declarations. A two-dimensional array b with two rows and two columns could be declared and initialized with nested array initializers as follows: int b[][] = { { 1, 2 }, { 3, 4 } }; The initializer values are grouped by row in braces. So, 1 and 2 initialize b[ 0][ 0] and b[ 0][ 1], and 3 and 4 initialize b[ 1][ 0] and b[ 1][ 1]. The compiler determines the number of rows by counting the number of nested array initializers (represented by sets of braces within the outer braces) in the array initializer. The compiler determines the number of columns in a row by counting the initializer values in the array initializer for that row. In Java, multidimensional arrays are maintained as arrays of one-dimensional arrays. So, the array b in the preceding declaration is actually composed of three separate onedimensional arrays. The array b itself is a one-dimensional array containing two elements. Each element is a reference to a one-dimensional array of int variables. Two-Dimensional Arrays with Rows of Different Lengths The manner in which Java represents multidimensional arrays makes them quite flexible. In fact, the lengths of the rows in array b are not required to be the same. For example, int b[][] = { { 1, 2 }, { 3, 4, 5 } }; creates integer array b with two elements (determined by the number of nested array initializers) that represent the rows of the two-dimensional array. Each element of b is a ref-

30 308 Arrays Chapter 7 erence to a one-dimensional array of int variables. The int array for row 0 is a onedimensional array with two elements (1 and 2 ) and the int array for row 1 is a one-dimensional array with three elements ( 3, 4 and 5 ). Creating Two-Dimensional Arrays with Array-Creation Expressions A multidimensional array with the same number of columns in every row can be created with an array-creation expression. For example, the following lines declare array b and assign it a reference to a three-by-four array: int b[][]; b = new int [ 3 ][ 4 ]; In this case, we use the literal values 3 and 4 to specify the number of rows and number of columns, respectively, but this is not required. Programs also can use variables to specify array dimensions. As with one-dimensional arrays, the elements of a multidimensional array are initialized when the array object is created. A multidimensional array in which each row has a different number of columns can be created as follows: int b[][]; b = new int [ 2 ][ ]; // create 2 rows b[ 0 ] = new int [ 5 ]; // create 5 columns for row 0 b[ 1 ] = new int [ 3 ]; // create 3 columns for row 1 The preceding statements create a two-dimensional array with two rows. Row 0 has five columns, and row 1 has three columns. Two-Dimensional Array Example: Displaying Element Values The applet of Fig demonstrates initializing two-dimensional arrays with array initializers and using nested for loops (lines 31 38) to traverse the arrays (i.e., manipulate every element of each array). 1 // Fig. 7.14: InitArray.java 2 // Initializing two-dimensional arrays. 3 import java.awt.container; 4 import javax.swing.*; 5 6 public class InitArray extends JApplet { 7 JTextArea outputarea; 8 9 // set up GUI and initialize applet 10 public void init() 11 { 12 outputarea = new JTextArea(); 13 Container container = getcontentpane(); 14 container.add( outputarea ); int array1[][] = { { 1, 2, 3 }, { 4, 5, 6 } }; int array2[][] = { { 1, 2 }, { 3 }, { 4, 5, 6 } }; Fig Initializing two-dimensional arrays. (Part 1 of 2.)

31 Chapter 7 Arrays outputarea.settext( "Values in array1 by row are\n" ); 20 buildoutput( array1 ); outputarea.append( "\nvalues in array2 by row are\n" ); 23 buildoutput( array2 ); } // end method init // append rows and columns of an array to outputarea 28 public void buildoutput( int array[][] ) 29 { outputarea.append( "\n" ); 38 } 39 // loop through array's rows for ( int row = 0 ; row < array.length; row++ ) { // loop through columns of current row for ( int column = 0 ; column < array[ row ].length; column++ ) outputarea.append( array[ row ][ column ] + " " ); 40 } // end method buildoutput } // end class InitArray Fig Initializing two-dimensional arrays. (Part 2 of 2.) The program declares two arrays in method init. The declaration of array1 (line 16) uses nested array initializers to initialize the first row of the array to the values 1, 2 and 3, and the second row of the array to the values 4, 5 and 6. The declaration of array2 (line 17) uses nested initializers of different lengths. In this case, the first row is initialized to have two elements with values 1 and 2, respectively. The second row is initialized to have one element with value 3. The third row is initialize to have three elements with the values 4, 5 and 6, respectively. Line 20 of method init calls method buildoutput (declared in lines 28 40) to append each array s elements to textarea outputarea. Method buildoutput specifies the array parameter as int array[][] to indicate that the method receives a two-dimensional array as an argument. The nested for statement (lines 31 38) outputs the rows of a two-dimensional array. In the outer for statement, the expression array.length deter-

32 310 Arrays Chapter 7 mines the number of rows in the array. In the inner for statement, the expression array[ row ].length determines the number of columns in the current row of the array. This condition enables the loop to determine the exact number of columns in each row. Common Multidimensional-Array Manipulations Performed with for Statements Many common array manipulations use for statements. As an example, the following for statement sets all the elements in the third row of array a in Fig to zero: for ( int column = 0 ; column < a[ 2 ].length; column++) a[ 2 ][ column ] = 0 ; We specified the third row; therefore, we know that the first index is always 2 ( 0 is the first row, and 1 is the second row). This for loop varies only the second index (i.e., the column index). The preceding for statement is equivalent to the assignment statements a[ 2 ][ 0 ] = 0 ; a[ 2 ][ 1 ] = 0 ; a[ 2 ][ 2 ] = 0 ; a[ 2 ][ 3 ] = 0 ; The following nested for statement totals the values of all the elements in array a : int total = 0 ; for ( int row = 0 ; row < a.length; row++ ) for ( int column = 0 ; column < a[ row ].length; column++ ) total += a[ row ][ column ]; This for statement totals the array elements one row at a time. The outer for statement begins by setting the row index to 0 so that the elements of the first row may be totaled by the inner for statement. The outer for statement then increments row to 1 so that the second row can be totaled. Then, the outer for statement increments row to 2 so that the third row can be totaled. The result can be displayed when the nested for statement terminates. Two-Dimensional Array Example: Summarizing Student s Exam Grades The applet of Fig performs several other common array manipulations on the threeby-four array grades. Each row of the array represents a student, and each column represents a grade on one of the four exams the students took during the semester. Four methods perform the array manipulations. Method minimum (lines 48 65) determines the lowest grade of any student for the semester. Method maximum (lines 68 85) determines the highest grade of any student for the semester. Method average (lines 88 99) determines a particular student s semester average. Method buildstring (lines ) appends the two-dimensional array to string output in a tabular format. Methods minimum, maximum and buildstring each use array grades and the variables students (number of rows in the array) and exams (number of columns in the array). Each method loops through array grades by using nested for statements for example, the nested for statement from the declaration of method minimum (lines 54 61). The outer for statement sets row (the row index) to 0 so that the elements of the first row can be compared with variable lowgrade in the body of the inner for statement. The inner

33 Chapter 7 Arrays // Fig. 7.15: DoubleArray.java 2 // Two-dimensional array example. 3 import java.awt.*; 4 import javax.swing.*; 5 6 public class DoubleArray extends JApplet { int students, exams; 12 String output; 13 JTextArea outputarea; // initialize fields 16 public void init() 17 { 18 students = grades.length; // number of students 19 exams = grades[ 0 ].length; // number of exams // create JTextArea and attach to applet 22 outputarea = new JTextArea(); 23 Container container = getcontentpane(); 24 container.add( outputarea ); // build output string 27 output = "The array is:\n"; int grades[][] = { { 77, 68, 86, 73 }, { 96, 87, 89, 81 }, { 70, 90, 86, 81 } }; buildstring(); 30 // call methods minimum and maximum 31 output += "\n\nlowest grade: " + minimum() + 32 "\nhighest grade: " + maximum() + "\n"; // call method average to calculate each student's average 35 for ( int counter = 0 ; counter < students; counter++ ) 36 output += "\naverage for student " + counter + " is " // change outputarea's display font average( grades[ counter ] ); // pass one row of array grades 40 outputarea.setfont( new Font( "Monospaced", Font. PLAIN, 12 ) ); // place output string in outputarea 43 outputarea.settext( output ); } // end method init // find minimum grade 48 public int minimum() 49 { 50 // assume first element of grades array is smallest 51 int lowgrade = grades[ 0 ][ 0 ]; 52 Fig Two-dimensional arrays. (Part 1 of 3.)

34 312 Arrays Chapter 7 53 // loop through rows of grades array 54 for ( int row = 0 ; row < students; row++ ) // loop through columns of current row 57 for ( int column = 0 ; column < exams; column++ ) // if grade is less than lowgrade, assign it to lowgrade 60 if ( grades[ row ][ column ] < lowgrade ) 61 lowgrade = grades[ row ][ column ]; return lowgrade; // return lowest grade } // end method minimum // find maximum grade 68 public int maximum() 69 { 70 // assume first element of grades array is largest 71 int highgrade = grades[ 0 ][ 0 ]; // loop through rows of grades array 74 for ( int row = 0 ; row < students; row++ ) // loop through columns of current row 77 for ( int column = 0 ; column < exams; column++ ) // if grade is greater than highgrade, assign it to highgrade 80 if ( grades[ row ][ column ] > highgrade ) 81 highgrade = grades[ row ][ column ]; return highgrade; // return highest grade } // end method maximum // determine average grade for particular student (or set of grades) public double average( int setofgrades[] ) { int total = 0 ; // initialize total // sum grades for one student for ( int count = 0 ; count < setofgrades.length; count++ ) total += setofgrades[ count ]; // return average of grades return ( double ) total / setofgrades.length; } // end method average 101 // build output string 102 public void buildstring() 103 { 104 output += " " ; // used to align column heads 105 Fig Two-dimensional arrays. (Part 2 of 3.)

35 Chapter 7 Arrays // create column heads 107 for ( int counter = 0 ; counter < exams; counter++ ) 108 output += "[" + counter + "] " ; // create rows/columns of text representing array grades 111 for ( int row = 0 ; row < students; row++ ) { 112 output += "\ngrades[" + row + "] " ; for ( int column = 0 ; column < exams; column++ ) 115 output += grades[ row ][ column ] + " " ; 116 } } // end method buildstring } // end class DoubleArray Fig Two-dimensional arrays. (Part 3 of 3.) for statement loops through the four grades of a particular row and compares each grade with lowgrade. If a grade is less than lowgrade, lowgrade is set to that grade. The outer for statement then increments the row index by 1, and the elements of the second row are compared with variable lowgrade. The outer for statement then increments the row index to 2, and the elements of the third row are compared with variable lowgrade. When execution of the nested statement is complete, lowgrade contains the smallest grade in the two-dimensional array. Method maximum works similarly to method minimum. Method average takes one argument a one-dimensional array of test results for a particular student. When line 37 calls average, the argument is grades[ counter ], which specifies that a particular row of the two-dimensional array grades should be passed to average. For example, the argument grades[ 1] represents the four values (a one-dimensional array of grades) stored in the second row of the two-dimensional array grades. Remember that, in Java, a two-dimensional array is an array with elements that are one-dimensional arrays. Method average calculates the sum of the array elements, divides the total by the number of test results and returns the floating-point result as a double value (line 97).

Arrays Introduction. Group of contiguous memory locations. Each memory location has same name Each memory location has same type

Arrays Introduction. Group of contiguous memory locations. Each memory location has same name Each memory location has same type Array Arrays Introduction Group of contiguous memory locations Each memory location has same name Each memory location has same type Remain same size once created Static entries 1 Name of array (Note that

More information

Arrays (Deitel chapter 7)

Arrays (Deitel chapter 7) Arrays (Deitel chapter 7) Plan Arrays Declaring and Creating Arrays Examples Using Arrays References and Reference Parameters Passing Arrays to Methods Sorting Arrays Searching Arrays: Linear Search and

More information

Chapter 6 Arrays and Strings Prentice Hall, Inc. All rights reserved.

Chapter 6 Arrays and Strings Prentice Hall, Inc. All rights reserved. 1 Chapter 6 Arrays and Strings Introduction 2 Arrays Data structures Related data items of same type Reference type Remain same size once created Fixed-length entries 3 Name of array (note that all elements

More information

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 7/e This chapter serves as an introduction to data structures. Arrays are data structures consisting of related data items of the same type. In Chapter 10, we discuss C s notion of

More information

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 6/e 1992-2010 by Pearson Education, Inc. 1992-2010 by Pearson Education, Inc. 1992-2010 by Pearson Education, Inc. This chapter serves as an introduction to the important topic of data

More information

C Arrays Pearson Education, Inc. All rights reserved.

C Arrays Pearson Education, Inc. All rights reserved. 1 6 C Arrays 2 Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end:

More information

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) Chapter - Arrays 1.1 Introduction 2.1 Introduction.2 Arrays.3 Declaring Arrays. Examples Using Arrays.5 Passing Arrays to Functions.6 Sorting Arrays. Case Study: Computing Mean, Median and Mode Using Arrays.8

More information

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types Chapter 4 - Arrays 1 4.1 Introduction 4.2 Arrays 4.3 Declaring Arrays 4.4 Examples Using Arrays 4.5 Passing Arrays to Functions 4.6 Sorting Arrays 4.7 Case Study: Computing Mean, Median and Mode Using

More information

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd El-Shorouk Academy Acad. Year : 2013 / 2014 High Institute of Computer Science & Information Technology Term : 1 st Year : 2 nd Computer Science Department Object Oriented Programming Section (1) Arrays

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. Data structures Collections of related data items. Discussed in depth in Chapters 16 21. Array objects Data

More information

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables 1 6 C Arrays 6.2 Arrays 2 Array Group of consecutive memory locations Same name and type To refer to an element, specify Array name + position number arrayname[ position number ] First element at position

More information

Chapter 6 SINGLE-DIMENSIONAL ARRAYS

Chapter 6 SINGLE-DIMENSIONAL ARRAYS Chapter 6 SINGLE-DIMENSIONAL ARRAYS Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk What is an Array? A single array variable can reference

More information

Chapter 5 - Methods Prentice Hall, Inc. All rights reserved.

Chapter 5 - Methods Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Methods 2003 Prentice Hall, Inc. All rights reserved. 2 Introduction Modules Small pieces of a problem e.g., divide and conquer Facilitate design, implementation, operation and maintenance

More information

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections C++ Programming Chapter 6 Arrays and Vectors Yih-Peng Chiou Room 617, BL Building (02) 3366-3603 3603 ypchiou@cc.ee.ntu.edu.tw Photonic Modeling and Design Lab. Graduate Institute of Photonics and Optoelectronics

More information

Chapter 6 - Methods Prentice Hall. All rights reserved.

Chapter 6 - Methods Prentice Hall. All rights reserved. Chapter 6 - Methods 1 Outline 6.1 Introduction 6.2 Program Modules in Java 6.3 Math Class Methods 6.4 Methods 6.5 Method Definitions 6.6 Argument Promotion 6.7 Java API Packages 6.8 Random-Number Generation

More information

Instructor: Eng.Omar Al-Nahal

Instructor: Eng.Omar Al-Nahal Faculty of Engineering & Information Technology Software Engineering Department Computer Science [2] Lab 6: Introduction in arrays Declaring and Creating Arrays Multidimensional Arrays Instructor: Eng.Omar

More information

C++ PROGRAMMING SKILLS Part 4: Arrays

C++ PROGRAMMING SKILLS Part 4: Arrays C++ PROGRAMMING SKILLS Part 4: Arrays Outline Introduction to Arrays Declaring and Initializing Arrays Examples Using Arrays Sorting Arrays: Bubble Sort Passing Arrays to Functions Computing Mean, Median

More information

Arrays Data structures Related data items of same type Remain same size once created Fixed-length entries

Arrays Data structures Related data items of same type Remain same size once created Fixed-length entries CBOP3203 Arrays Data structures Related data items of same type Remain same size once created Fixed-length entries A 12 element Array Index Also called subscript Position number in square brackets Must

More information

Part 8 Methods. scope of declarations method overriding method overloading recursions

Part 8 Methods. scope of declarations method overriding method overloading recursions Part 8 Methods scope of declarations method overriding method overloading recursions Modules Small pieces of a problem e.g., divide and conquer 6.1 Introduction Facilitate design, implementation, operation

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 06 / 11 / 2015 Instructor: Michael Eckmann Today s Topics Comments and/or Questions? Sorting Searching Michael Eckmann - Skidmore College - CS 106 - Summer 2015

More information

Fundamentals of Programming Session 14

Fundamentals of Programming Session 14 Fundamentals of Programming Session 14 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Methods (Deitel chapter 6)

Methods (Deitel chapter 6) Methods (Deitel chapter 6) 1 Plan 2 Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods

More information

C Arrays. O b j e c t i v e s In this chapter, you ll:

C Arrays.   O b j e c t i v e s In this chapter, you ll: www.thestudycampus.com C Arrays O b j e c t i v e s In this chapter, you ll: Use the array data structure to represent lists and tables of values. Define an array, initialize an array and refer to individual

More information

Methods (Deitel chapter 6)

Methods (Deitel chapter 6) 1 Plan 2 Methods (Deitel chapter ) Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods

More information

For searching and sorting algorithms, this is particularly dependent on the number of data elements.

For searching and sorting algorithms, this is particularly dependent on the number of data elements. Looking up a phone number, accessing a website and checking the definition of a word in a dictionary all involve searching large amounts of data. Searching algorithms all accomplish the same goal finding

More information

Lecture 04 FUNCTIONS AND ARRAYS

Lecture 04 FUNCTIONS AND ARRAYS Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions

More information

C: How to Program. Week /Apr/23

C: How to Program. Week /Apr/23 C: How to Program Week 9 2007/Apr/23 1 Review of Chapters 1~5 Chapter 1: Basic Concepts on Computer and Programming Chapter 2: printf and scanf (Relational Operators) keywords Chapter 3: if (if else )

More information

Objectives of This Chapter

Objectives of This Chapter Chapter 6 C Arrays Objectives of This Chapter Array data structures to represent the set of values. Defining and initializing arrays. Defining symbolic constant in a program. Using arrays to store, list,

More information

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips Lab6 Array I Objectivities 1. Using rand to generate random numbers and using srand to seed the random-number generator. 2. Declaring, initializing and referencing arrays. 3. The follow-up questions and

More information

Programming for Engineers Arrays

Programming for Engineers Arrays Programming for Engineers Arrays ICEN 200 Spring 2018 Prof. Dola Saha 1 Array Ø Arrays are data structures consisting of related data items of the same type. Ø A group of contiguous memory locations that

More information

Deitel Series Page How To Program Series

Deitel Series Page How To Program Series Deitel Series Page How To Program Series Android How to Program C How to Program, 7/E C++ How to Program, 9/E C++ How to Program, Late Objects Version, 7/E Java How to Program, 9/E Java How to Program,

More information

The first applet we shall build will ask the user how many times the die is to be tossed. The request is made by utilizing a JoptionPane input form:

The first applet we shall build will ask the user how many times the die is to be tossed. The request is made by utilizing a JoptionPane input form: Lecture 5 In this lecture we shall discuss the technique of constructing user-defined methods in a class. The discussion will be centered about an experiment of tossing a die a specified number of times.

More information

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7) Array Basics: Outline Arrays (Savitch, Chapter 7) TOPICS Array Basics Arrays in Classes and Methods Programming with Arrays Searching and Sorting Arrays Multi-Dimensional Arrays Static Variables and Constants

More information

Chapter 6. Arrays. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Chapter 6. Arrays. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 Arrays Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 Chapter 6 - Arrays 6.1 Introduction 6.2 Arrays 6.3 Declaring Arrays 6.4 Examples Using Arrays

More information

Function Call Stack and Activation Records

Function Call Stack and Activation Records 71 Function Call Stack and Activation Records To understand how C performs function calls, we first need to consider a data structure (i.e., collection of related data items) known as a stack. Students

More information

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad CHAPTER 3 ARRAYS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Arrays 3. Declaring Arrays 4. Examples Using Arrays 5. Multidimensional Arrays 6. Multidimensional Arrays Examples 7. Examples Using

More information

Arrays. Week 4. Assylbek Jumagaliyev

Arrays. Week 4. Assylbek Jumagaliyev Arrays Week 4 Assylbek Jumagaliyev a.jumagaliyev@iitu.kz Introduction Arrays Structures of related data items Static entity (same size throughout program) A few types Pointer-based arrays (C-like) Arrays

More information

CSE101-lec#19. Array searching and sorting techniques. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

CSE101-lec#19. Array searching and sorting techniques. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming CSE101-lec#19 Array searching and sorting techniques Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU Outline Introduction Linear search Binary search Bubble sort Introduction The process of finding

More information

Multiple-Subscripted Arrays

Multiple-Subscripted Arrays Arrays in C can have multiple subscripts. A common use of multiple-subscripted arrays (also called multidimensional arrays) is to represent tables of values consisting of information arranged in rows and

More information

Assignment Checklist. Prelab Activities. Lab Exercises. Labs Provided by Instructor. Postlab Activities. Section:

Assignment Checklist. Prelab Activities. Lab Exercises. Labs Provided by Instructor. Postlab Activities. Section: 7 Arrays Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end: then

More information

Arrays Pearson Education, Inc. All rights reserved.

Arrays Pearson Education, Inc. All rights reserved. 1 7 Arrays 7.1 Introduction 7.2 Arrays 7.3 Declaring and Creating Arrays 7.4 Examples Using Arrays 7.5 Case Study: Card Shuffling and Dealing Simulation 7.6 Enhanced for Statement 7.7 Passing Arrays to

More information

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays) Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays) In this lecture, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of

More information

Computer Programming Lecture 14 Arrays (Part 2)

Computer Programming Lecture 14 Arrays (Part 2) Computer Programming Lecture 14 Arrays (Part 2) Assist.Prof.Dr. Nükhet ÖZBEK Ege University Department of Electrical & Electronics Engineering nukhet.ozbek@ege.edu.tr 1 Topics The relationship between

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Java application A computer program that executes when you use the java command to launch the Java Virtual Machine

More information

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva All copyrights reserved - KV NAD, Aluva Dinesh Kumar Ram PGT(CS) KV NAD Aluva Overview Looping Introduction While loops Syntax Examples Points to Observe Infinite Loops Examples using while loops do..

More information

C/C++ Programming Lecture 18 Name:

C/C++ Programming Lecture 18 Name: . The following is the textbook's code for a linear search on an unsorted array. //***************************************************************** // The searchlist function performs a linear search

More information

Control Statements. Musa M. Ameen Computer Engineering Dept.

Control Statements. Musa M. Ameen Computer Engineering Dept. 2 Control Statements Musa M. Ameen Computer Engineering Dept. 1 OBJECTIVES In this chapter you will learn: To use basic problem-solving techniques. To develop algorithms through the process of topdown,

More information

Chapter 5: Enhancing Classes

Chapter 5: Enhancing Classes Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition by John Lewis, William Loftus, and Cara Cocking Java Software Solutions is published by

More information

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 1 ARRAYS Arrays 2 Arrays Structures of related data items Static entity (same size

More information

References. Chapter 5: Enhancing Classes. Enhancing Classes. The null Reference. Java Software Solutions for AP* Computer Science A 2nd Edition

References. Chapter 5: Enhancing Classes. Enhancing Classes. The null Reference. Java Software Solutions for AP* Computer Science A 2nd Edition Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis, William Loftus, and Cara Cocking Java Software Solutions is published

More information

Object Oriented Programming. Java-Lecture 6 - Arrays

Object Oriented Programming. Java-Lecture 6 - Arrays Object Oriented Programming Java-Lecture 6 - Arrays Arrays Arrays are data structures consisting of related data items of the same type In Java arrays are objects -> they are considered reference types

More information

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Lesson 06 Arrays MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Array An array is a group of variables (called elements or components) containing

More information

Chapter 9 Introduction to Arrays. Fundamentals of Java

Chapter 9 Introduction to Arrays. Fundamentals of Java Chapter 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

More information

Chapter 7 : Arrays (pp )

Chapter 7 : Arrays (pp ) Page 1 of 45 Printer Friendly Version User Name: Stephen Castleberry email Id: scastleberry@rivercityscience.org Book: A First Book of C++ 2007 Cengage Learning Inc. All rights reserved. No part of this

More information

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Up to here Not included in program Java collections framework prebuilt data structures interfaces and methods for manipulating

More information

19 Much that I bound, I could not free; Much that I freed returned to me. Lee Wilson Dodd

19 Much that I bound, I could not free; Much that I freed returned to me. Lee Wilson Dodd 19 Much that I bound, I could not free; Much that I freed returned to me. Lee Wilson Dodd Will you walk a little faster? said a whiting to a snail, There s a porpoise close behind us, and he s treading

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba Before writing a program to solve a problem, have a thorough understanding of the problem and a carefully planned approach to solving it. Understand the types of building

More information

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Covered in this chapter Classes Objects Methods Parameters double primitive type } Create a new class (GradeBook) } Use it to create an object.

More information

142

142 Scope Rules Thus, storage duration does not affect the scope of an identifier. The only identifiers with function-prototype scope are those used in the parameter list of a function prototype. As mentioned

More information

egrapher Language Reference Manual

egrapher Language Reference Manual egrapher Language Reference Manual Long Long: ll3078@columbia.edu Xinli Jia: xj2191@columbia.edu Jiefu Ying: jy2799@columbia.edu Linnan Wang: lw2645@columbia.edu Darren Chen: dsc2155@columbia.edu 1. Introduction

More information

APCS Semester #1 Final Exam Practice Problems

APCS Semester #1 Final Exam Practice Problems Name: Date: Per: AP Computer Science, Mr. Ferraro APCS Semester #1 Final Exam Practice Problems The problems here are to get you thinking about topics we ve visited thus far in preparation for the semester

More information

PLD Semester Exam Study Guide Dec. 2018

PLD Semester Exam Study Guide Dec. 2018 Covers material from Chapters 1-8. Semester Exam will be built from these questions and answers, though they will be re-ordered and re-numbered and possibly worded slightly differently than on this study

More information

8/2/10. Looking for something COMP 10 EXPLORING COMPUTER SCIENCE. Where is the book Modern Interiors? Lecture 7 Searching and Sorting TODAY'S OUTLINE

8/2/10. Looking for something COMP 10 EXPLORING COMPUTER SCIENCE. Where is the book Modern Interiors? Lecture 7 Searching and Sorting TODAY'S OUTLINE Looking for something COMP 10 EXPLORING COMPUTER SCIENCE Where is the book Modern Interiors? Lecture 7 Searching and Sorting TODAY'S OUTLINE Searching algorithms Linear search Complexity Sorting algorithms

More information

Outline Introduction Arrays Declaring Arrays Examples Using Arrays Passing Arrays to Functions Sorting Arrays

Outline Introduction Arrays Declaring Arrays Examples Using Arrays Passing Arrays to Functions Sorting Arrays Arrays Outline 1 Introduction 2 Arrays 3 Declaring Arrays 4 Examples Using Arrays 5 Passing Arrays to Functions 6 Sorting Arrays 7 Case Study: Computing Mean, Median and Mode Using Arrays 8 Searching Arrays

More information

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 ARRAYS ~ VECTORS KOM3191 Object-Oriented Computer Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2 What is an array? Arrays

More information

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation. Lab 4 Functions Introduction: A function : is a collection of statements that are grouped together to perform an operation. The following is its format: type name ( parameter1, parameter2,...) { statements

More information

Chapter 4 Control Structures: Part 2

Chapter 4 Control Structures: Part 2 Chapter 4 Control Structures: Part 2 1 2 Essentia ls of Counter-Controlled Repetition Counter-controlled repetition requires: Control variable (loop counter) Initial value of the control variable Increment/decrement

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 Two ways to pass arguments to functions in many programming languages are pass-by-value and pass-by-reference. When an argument is passed by value, a copy of the argument s value is made and passed (on

More information

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions Faculty of Engineering Computer Engineering Department Islamic University of Gaza 2013 C++ Programming Language Lab # 6 Functions C++ Programming Language Lab # 6 Functions Objective: To be familiar with

More information

Course PJL. Arithmetic Operations

Course PJL. Arithmetic Operations Outline Oman College of Management and Technology Course 503200 PJL Handout 5 Arithmetic Operations CS/MIS Department 1 // Fig. 2.9: Addition.java 2 // Addition program that displays the sum of two numbers.

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 9/e Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Searching data involves determining whether a value (referred to as the search key) is present in the data

More information

In this chapter you ll learn:

In this chapter you ll learn: Much that I bound, I could not free; Much that I freed returned to me. Lee Wilson Dodd Will you walk a little faster? said a whiting to a snail, There s a porpoise close behind us, and he s treading on

More information

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

Lesson 9: Introduction To Arrays (Updated for Java 1.5 Modifications by Mr. Dave Clausen) Lesson 9: Introduction To Arrays (Updated for Java 1.5 Modifications by Mr. Dave Clausen) 1 Lesson 9: Introduction Objectives: To Arrays Write programs that handle collections of similar items. Declare

More information

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED Outline - Function Definitions - Function Prototypes - Data

More information

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling Frames, GUI and events Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling Introduction to Swing The Java AWT (Abstract Window Toolkit)

More information

Chapter 7 Array. Array. C++, How to Program

Chapter 7 Array. Array. C++, How to Program Chapter 7 Array C++, How to Program Deitel & Deitel Spring 2016 CISC 1600 Yanjun Li 1 Array Arrays are data structures containing related data items of same type. An array is a consecutive group of memory

More information

Contents Chapter 1 Introduction to Programming and the Java Language

Contents Chapter 1 Introduction to Programming and the Java Language Chapter 1 Introduction to Programming and the Java Language 1.1 Basic Computer Concepts 5 1.1.1 Hardware 5 1.1.2 Operating Systems 8 1.1.3 Application Software 9 1.1.4 Computer Networks and the Internet

More information

Lesson 12: Recursion, Complexity, Searching and Sorting. Modifications By Mr. Dave Clausen Updated for Java 1_5

Lesson 12: Recursion, Complexity, Searching and Sorting. Modifications By Mr. Dave Clausen Updated for Java 1_5 Lesson 12: Recursion, Complexity, Searching and Sorting Modifications By Mr. Dave Clausen Updated for Java 1_5 1 Lesson 12: Recursion, Complexity, and Searching and Sorting Objectives: Design and implement

More information

GUI Forms and Events, Part II

GUI Forms and Events, Part II GUI Forms and Events, Part II Quick Start Compile step once always mkdir labs javac PropertyTax6.java cd labs Execute step mkdir 6 java PropertyTax6 cd 6 cp../5/propertytax5.java PropertyTax6.java Submit

More information

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

More information

C: How to Program. Week /Apr/16

C: How to Program. Week /Apr/16 C: How to Program Week 8 2006/Apr/16 1 Storage class specifiers 5.11 Storage Classes Storage duration how long an object exists in memory Scope where object can be referenced in program Linkage specifies

More information

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode STUDENT OUTLINE Lesson 8: Structured Programming, Control Structures, if- Statements, Pseudocode INTRODUCTION: This lesson is the first of four covering the standard control structures of a high-level

More information

CS112 Lecture: Repetition Statements

CS112 Lecture: Repetition Statements CS112 Lecture: Repetition Statements Objectives: Last revised 2/18/05 1. To explain the general form of the java while loop 2. To introduce and motivate the java do.. while loop 3. To explain the general

More information

C Functions. 5.2 Program Modules in C

C Functions. 5.2 Program Modules in C 1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking

More information

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CHAPTER 4 FUNCTIONS. 4.1 Introduction CHAPTER 4 FUNCTIONS 4.1 Introduction Functions are the building blocks of C++ programs. Functions are also the executable segments in a program. The starting point for the execution of a program is main

More information

STUDENT LESSON A12 Iterations

STUDENT LESSON A12 Iterations STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of

More information

Control Statements: Part 1

Control Statements: Part 1 4 Let s all move one place on. Lewis Carroll Control Statements: Part 1 The wheel is come full circle. William Shakespeare How many apples fell on Newton s head before he took the hint! Robert Frost All

More information

Arrays. Outline. Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Prentice Hall, Inc. All rights reserved.

Arrays. Outline. Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Prentice Hall, Inc. All rights reserved. Arrays 1 Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Multidimensional Arrays 2 Multiple subscripts a[ i ][ j ] Tables with rows and columns Specify row, then column

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Sorting Algorithms. Array Data is being arranged in ascending order using the bubble sort algorithm. #1 #2 #3 #4 #5 #6 #7

Sorting Algorithms. Array Data is being arranged in ascending order using the bubble sort algorithm. #1 #2 #3 #4 #5 #6 #7 Sorting Algorithms One of the fundamental problems of computer science is ordering a list of items. There s a plethora of solutions to this problem, known as sorting algorithms. Some sorting algorithms

More information

2.8. Decision Making: Equality and Relational Operators

2.8. Decision Making: Equality and Relational Operators Page 1 of 6 [Page 56] 2.8. Decision Making: Equality and Relational Operators A condition is an expression that can be either true or false. This section introduces a simple version of Java's if statement

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;

More information

Class 27: Nested Classes and an Introduction to Trees

Class 27: Nested Classes and an Introduction to Trees Introduction to Computation and Problem Solving Class 27: Nested Classes and an Introduction to Trees Prof. Steven R. Lerman and Dr. V. Judson Harward Goals To explain in more detail the different types

More information

4.1 COMPUTATIONAL THINKING AND PROBLEM-SOLVING

4.1 COMPUTATIONAL THINKING AND PROBLEM-SOLVING 4.1 COMPUTATIONAL THINKING AND PROBLEM-SOLVING 4.1.2 ALGORITHMS ALGORITHM An Algorithm is a procedure or formula for solving a problem. It is a step-by-step set of operations to be performed. It is almost

More information

ARRAYS, RECURSION, AND COMPLEXITY

ARRAYS, RECURSION, AND COMPLEXITY ARRAYS, RECURSION, AND COMPLEXITY Chapter 10 Introduction to Arrays Chapter 11 Classes Continued Chapter 12 Arrays Continued 5 hrs. 5 hrs. 4.5 hrs. Estimated Time for Unit: 14.5 hours CHAPTER 10 INTRODUCTION

More information

DEMYSTIFYING PROGRAMMING: CHAPTER SIX METHODS (TOC DETAILED) CHAPTER SIX: METHODS 1

DEMYSTIFYING PROGRAMMING: CHAPTER SIX METHODS (TOC DETAILED) CHAPTER SIX: METHODS 1 DEMYSTIFYING PROGRAMMING: CHAPTER SIX METHODS (TOC DETAILED) CHAPTER SIX: METHODS 1 Objectives 1 6.1 Methods 1 void or return 1 Parameters 1 Invocation 1 Pass by value 1 6.2 GUI 2 JButton 2 6.3 Patterns

More information

Arrays and Applications

Arrays and Applications Arrays and Applications 60-141: Introduction to Algorithms and Programming II School of Computer Science Term: Summer 2014 Instructor: Dr. Asish Mukhopadhyay What s an array Let a 0, a 1,, a n-1 be a sequence

More information

Chapter 3: Operators, Expressions and Type Conversion

Chapter 3: Operators, Expressions and Type Conversion 101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To

More information

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 9/e Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Copyright 1992-2012 by Pearson Copyright 1992-2012 by Pearson Before writing a program to solve a problem, have

More information