7Arrays and ArrayLists
Objectives
In this chapter you’ll:
Learn what arrays are.
Use arrays to store data in and
Use variable-length argument
lists.
Read command-line
arguments into a program.
Build an object-oriented
2Chapter 7 Arrays and ArrayLists
Self-Review Exercises
7.1 Fill in the blank(s) in each of the following statements:
a) Lists and tables of values can be stored in and .
b) An array is a group of (called elements or components) containing values that
all have the same .
c) The allows you to iterate through an array’s elements without using a counter.
d) The number used to refer to a particular array element is called the element’s .
e) An array that uses two indices is referred to as a(n) array.
f) Use the enhanced for statement to walk through double array numbers.
g) Command-line arguments are stored in .
h) Use the expression to receive the total number of arguments in a command
line. Assume that command-line arguments are stored in String[] args.
i) Given the command java MyClass test, the first command-line argument is .
j) A(n) in the parameter list of a method indicates that the method can receive
a variable number of arguments.
7.2 Determine whether each of the following is true or false. If false, explain why.
a) An array can store many different types of values.
b) An array index should normally be of type float.
c) An individual array element that’s passed to a method and modified in that method will
contain the modified value when the called method completes execution.
d) Command-line arguments are separated by commas.
7.3 Perform the following tasks for an array called fractions:
a) Declare a constant ARRAY_SIZE that’s initialized to 10.
b) Declare an array with ARRAY_SIZE elements of type double, and initialize the elements
to 0.
c) Refer to array element 4.
Self-Review Exercises 3
d) Assign the value 1.667 to array element 9.
e) Assign the value 3.333 to array element 6.
f) Sum all the elements of the array, using a for statement. Declare the integer variable x
as a control variable for the loop.
ANS:
7.4 Perform the following tasks for an array called table:
a) Declare and create the array as an integer array that has three rows and three columns.
Assume that the constant ARRAY_SIZE has been declared to be 3.
b) How many elements does the array contain?
c) Use a for statement to initialize each element of the array to the sum of its indices. As
sume that the integer variables x and y are declared as control variables.
ANS:
7.5 Find and correct the error in each of the following program segments:
a)
b)
c)
ANS: Error: Array indexing is performed incorrectly.
Correction: Change the statement to a[1][1] = 5;.
1double total = 0.0;
2for (int x = 0; x < fractions.length; x++)
3 total += fractions[x];
1for (int x = 0; x < table.length; x++)
2 for (int y = 0; y < table[x].length; y++)
3 table[x][y] = x + y;
1final int ARRAY_SIZE = 5;
2ARRAY_SIZE = 10;
1int[] b = new int[10];
2for (int i = 0; i <= b.length; i++)
3 b[i] = 1;
1int[][] a = {{1, 2}, {3, 4}};
2a[1, 1] = 5;
© 2018 Pearson Education, Inc., 330 Hudson Street, NY NY 10013. All rights reserved.
4Chapter 7 Arrays and ArrayLists
Exercises
NOTE: Solutions to the programming exercises are located in the ch07solutions folder.
Each exercise has its own folder named ex07_## where ## is a two-digit number represent-
ing the exercise number. For example, exercise 7.10’s solution is located in the folder ex-
07_10.
7.6 Fill in the blanks in each of the following statements:
a) One-dimensional array p contains four elements. The names of those elements are
, , and .
b) Naming an array, stating its type and specifying the number of dimensions in the array
is called the array.
c) In a two-dimensional array, the first index identifies the of an element and the
second index identifies the of an element.
d) An m-by-n array contains rows, columns and elements.
e) The name of the element in row 3 and column 5 of array d is .
7.7 Determine whether each of the following is true or false. If false, explain why.
a) To refer to a particular location or element within an array, we specify the name of the
array and the value of the particular element.
b) An array declaration reserves space for the array.
c) To indicate that 100 locations should be reserved for integer array p, you write the dec-
laration
p[100];
d) An application that initializes the elements of a 15-element array to zero must contain
at least one for statement.
e) An application that totals the elements of a two-dimensional array must contain nested
for statements.
7.8 Write Java statements to accomplish each of the following tasks:
a) Display the value of element 6 of array f.
b) Initialize each of the five elements of one-dimensional integer array g to 8.
c) Total the 100 elements of floating-point array c.
d) Copy 11-element array a into the first portion of array b, which contains 34 elements.
Exercises 5
e) Determine and display the smallest and largest values contained in 99-element floating-
point array w.
7.9 Consider a two-by-three integer array t.
b) How many rows does t have?
c) How many columns does t have?
d) How many elements does t have?
e) Write access expressions for all the elements in row 1 of t.
f) Write access expressions for all the elements in column 2 of t.
g) Write a single statement that sets the element of t in row 0 and column 1 to zero.
i) Write a nested for statement that initializes each element of t to zero.
j) Write a nested for statement that inputs the values for the elements of t from the user.
k) Write a series of statements that determines and displays the smallest value in t.
6Chapter 7 Arrays and ArrayLists
l) Write a single printf statement that displays the elements of the first row of t.
ANS: System.out.printf(“%d %d %d\n”, t[0][0], t[0][1], t[0][2]);
m) Write a statement that totals the elements of the third column of t. Do not use iteration.
n) Write a series of statements that displays the contents of t in tabular format. List the
column indices as headings across the top, and list the row indices at the left of each row.
7.10 (Sales Commissions) Use a one-dimensional array to solve the following problem: A com-
pany pays its salespeople on a commission basis. The salespeople receive $200 per week plus 9% of
their gross sales for that week. For example, a salesperson who grosses $5,000 in sales in a week re-
ceives $200 plus 9% of $5,000, or a total of $650. Write an application (using an array of counters)
7.11 Write statements that perform the following one-dimensional-array operations:
a) Set the 10 elements of integer array counts to zero.
b) Add one to each of the 15 elements of integer array bonus.
c) Display the five values of integer array bestScores in column format.
7.13 Label the elements of three-by-five two-dimensional array sales to indicate the order in
which they’re set to zero by the following program segment:
for (int row = 0; row < sales.length; row++) {
for (int col = 0; col < sales[row].length; col++) {
sales[row][col] = 0;
}
}
Special Section: Building Your Own Computer 7
Special Section: Building Your Own Computer
In the next several problems, we take a temporary diversion from the world of high-level language
programming to “peel open” a computer and look at its internal structure. We introduce machine-
language programming and write several machine-language programs. To make this an especially
valuable experience, we then build a computer (through the technique of software-based simula-
tion) on which you can execute your machine-language programs.
7.36 (Machine-Language Programming) Let’s create a computer called the Simpletron. As its
name implies, it’s a simple machine, but powerful. The Simpletron runs programs written in the
only language it directly understands: Simpletron Machine Language (SML).
The Simpletron contains an accumulator—a special register in which information is put
before the Simpletron uses that information in calculations or examines it in various ways. All the
of memory. The first two digits of each SML instruction are the operation code specifying the opera-
tion to be performed. SML operation codes are summarized in Fig. 7.1.
The last two digits of an SML instruction are the operand—the address of the memory location
containing the word to which the operation applies. Let’s consider several simple SML programs.
Operation code Meaning
Input/output operations:
Load/store operations:
Arithmetic operations:
Fig. 7.1 |Simpletron Machine Language (SML) operation codes. (Part 1 of 2.)
© 2018 Pearson Education, Inc., 330 Hudson Street, NY NY 10013. All rights reserved.
8Chapter 7 Arrays and ArrayLists
The first SML program (Fig. 7.2) reads two numbers from the keyboard and computes and
displays their sum. The instruction +1007 reads the first number from the keyboard and places it
into location 07 (which has been initialized to 0). Then instruction +1008 reads the next number
into location 08. The load instruction, +2007, puts the first number into the accumulator, and the
add instruction, +3008, adds the second number to the number in the accumulator. All SML arith-
metic instructions leave their results in the accumulator. The store instruction, +2109, places the result
back into memory location 09, from which the write instruction, +1109, takes the number and dis-
plays it (as a signed four-digit decimal number). The halt instruction, +4300, terminates execution.
The second SML program (Fig. 7.3) reads two numbers from the keyboard and determines
and displays the larger value. Note the use of the instruction +4107 as a conditional transfer of con-
trol, much the same as Javas if statement.
Transfer-of-control operations:
final int BRANCH = 40; Branch to a specific location in memory.
Location Number Instruction
00 +1007 (Read A)
01 +1008 (Read B)
Fig. 7.2 |SML program that reads two integers and computes their sum.
Location Number Instruction
00 +1009 (Read A)
Fig. 7.3 |SML program that reads two integers and determines the larger.
Operation code Meaning
Fig. 7.1 |Simpletron Machine Language (SML) operation codes. (Part 2 of 2.)
© 2018 Pearson Education, Inc., 330 Hudson Street, NY NY 10013. All rights reserved.
Special Section: Building Your Own Computer 9
Now write SML programs to accomplish each of the following tasks:
a) Use a sentinel-controlled loop to read 10 positive numbers. Compute and display their
sum.
ANS: Note: This program terminates when a negative number is input. The problem state-
b) Use a countercontrolled loop to read seven numbers, some positive and some negative,
and compute and display their average.
ANS:
00 +2018 (Load Counter)
01 +3121 (Subtract Termination)
02 +4211 (Branch zero to 11)
03 +2018 (Load Counter)
04 +3019 (Add Increment)
05 +2118 (Store Counter)
06 +1017 (Read Value)
07 +2016 (Load Sum)
08 +3017 (Add Value)
09 +2116 (Store Sum)
10 +4000 (Branch 00)
11 +2016 (Load Sum)
12 +3218 (Divide Counter)
13 +2120 (Store Result)
04 +4107 (Branch negative to 07)
05 +1109 (Write A)
06 +4300 (Halt)
07 +1110 (Write B)
08 +4300 (Halt)
09 +0000 (Variable A)
10 +0000 (Variable B)
Location Number Instruction
Fig. 7.3 |SML program that reads two integers and determines the larger.
© 2018 Pearson Education, Inc., 330 Hudson Street, NY NY 10013. All rights reserved.
10 Chapter 7 Arrays and ArrayLists
c) Read a series of numbers, and determine and display the largest number. The first num-
ber read indicates how many numbers should be processed.