Skip to main content
Contents
Dark Mode Prev Up Next Scratch ActiveCode Profile
\(
\newcommand{\lt}{<}
\newcommand{\gt}{>}
\newcommand{\amp}{&}
\definecolor{fillinmathshade}{gray}{0.9}
\newcommand{\fillinmath}[1]{\mathchoice{\colorbox{fillinmathshade}{$\displaystyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\textstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptscriptstyle\phantom{\,#1\,}$}}}
\)
Section 11.8 Assessment: Arrays 1
Subgoals for Evaluating Arrays.
Declaring and initialization of array
Set up a one dimensional table (i.e., one row) with 0 to (size - 1) elements
Upon instantiation of an array object, all elements contain default value for datatype stored in array OR values from the initializer list
Determine access or change of element, or action on entire array object, and update slots as needed (remembering assignment subgoals)
Evaluate expression within [ ] which will be the index for element to be accessed
arrayName[index]
returns value stored at that index
index must be between 0 and
arrayName.length
- 1, inclusive otherwise
IndexOutOfBounds
exception occurs
Changing value of an array element
Evaluate expression within [ ] which will be the index for element to be accessed
arrayName[index]
will now contain the value on the RHS of assignment statement
(remember the assignment subgoals for verifying data types and evaluating expressions)
(remember rules for index values)
Pass as argument - a copy of the reference to the instantiated array is passed to the method. This means that any changes made to the array elements inside the method are persistent. The one exception to this is if you assign the argument to reference a different array in memory.
Assignment - changes the reference to point to the array on the RHS of the assignment operator.
Exercises Exercises
1.
Q1: Assuming that the following declaration has been made, which of the following code segments correctly interchanges the value of
arr[0]
and
arr[5]
?
int [ ] arr = {5, 12, -22, 6, 11, 0, 26, 42, 99, 75};
Figure 11.8.1.
2.
Considering the following code, what are the values in numbers after execution?
int size = 8;
int [ ] numbers = new int[size];
for (int k = size / 2; k < size; k++)
numbers[k] = numbers[k-1] + size;
[0, 0, 0, 0, 8, 16, 24, 32]
[0, 1, 2, 3, 8, 16, 24, 32]
[8, 16, 24, 32, 40, 48, 52, 60]
3.
Q3: Considering the following code, what are the values in numbers after execution?
int [] numbers = {17, 34, 21, 42, 15, 69, 48, 25, 39};
int x = 3;
for (int k = 1; k < 9; k = k + x)
numbers[k] = numbers[k-1] + x;
{17, 20, 21, 42, 45, 69, 48, 51, 39}
{17, 20, 23, 26, 29, 32, 35, 38, 41}
{17, 37, 21, 42, 18, 69, 48, 28, 39}
{20, 23, 21, 42, 45, 69, 51, 54, 39}
{20, 34, 21, 45, 15, 69, 51, 25, 39}
You have attempted
of
activities on this page.