Section 11.1 Worked Example: Arrays - Instantiate and Alter
Subgoals for Evaluating Arrays.
- Set up array from 0 to size-1
- Evaluate data type of statements against array
-
Trace statements, updating slots as you go
- Remember assignment subgoals
Subsection 11.1.1
You can watch this video or read through the content below it.
Problem:
Given the initialized array:
int [] alpha;
Evaluate these statements and determine the value of all variables. If any error occurs, give the reason.
alpha = new int[5];
alpha[4] = 22;
alpha[0] = 10;
alpha[1] = alpha[4] - alpha[0];
alpha[2] = alpha[1] - alpha[0];
alpha[3] = alpha[alpha[2] - 1];
alpha[4] = alpha[alpha[3]];
Subsection 11.1.2 SG1: Set up array from 0 to size-1
alpha = new int[5];
![](external/Arrays/Figures/we1-init.png)
alpha
is declared as an array of ints- This statement allocates 5 slots for integers (first line are indexes, second line are values/content):
- The declared size of array is 5, so last valid index value is 4
- Notice that the array contains values of 0 because 0 is the default value for integers, the data type stored in the array.
Subsection 11.1.3 SG2: Evaluate data type of statements against array
alpha[4] = 22;
alpha[0] = 10;
alpha[1] = alpha[4] - alpha[0];
alpha[2] = alpha[1] - alpha[0];
alpha[3] = alpha[alpha[2] - 1];
alpha[4] = alpha[alpha[3]];
- Each of these statements only involve integers.
- Notice that whenever [ ] are used in a statement, we will be accessing the value stored at the index inside the [ ]. All accesses will result in an integer because we have an integer array.
- All of the array indexes on the left hand side of the assignment statements are within the bounds of the array (0 – 4).
- We can see that some of the index values on the right hand side of the array are within bounds, but we will need to evaluate them all to see if all are valid.
Subsection 11.1.4 SG3: Trace statements, updating slots as you go
We will evaluate the first two statements:
alpha[4] = 22;
alpha[0] = 10;
The resulting array is:
![](external/Arrays/Figures/we1-trace-1-2.png)
The next statement is:
alpha[1] = alpha[4] - alpha[0];
In index 1 (because of alpha[1]) we will store the result of (value at index 4 - value at index 0) which is 22 - 10, so 12 is stored at index 1.
![](external/Arrays/Figures/we1-trace-3.png)
Next:
alpha[2] = alpha[1] - alpha[0];
![](external/Arrays/Figures/we1-trace-5.png)
For the next statement,
alpha[3] = alpha[alpha[2] - 1];
, first determine the value of alpha[2] which is 2. Then look at alpha[2 - 1] which is alpha[1], or 12![](external/Arrays/Figures/we1-trace-4.png)
Finally, there is a problem with the last statement:
alpha[4] = alpha[alpha[3]];
First determine the value of alpha[3] which is 12. When we try to get alpha[12], it is out of bounds, and an IndexOutOfBounds
exception occurs with this statement.Subsection 11.1.5 Practice Pages
You have attempted of activities on this page.