Skip to main content

Section 11.3 Worked Example: Arrays - Traverse

Subgoals for Evaluating Arrays.

  1. Set up array from 0 to size-1
  2. Evaluate data type of statements against array
  3. Trace statements, updating slots as you go
    1. Remember assignment subgoals

Subsection 11.3.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[10];
for (int i = 0; i < 10; i++)
alpha[i] = i * 1;

Subsection 11.3.2 SG1: Set up array from 0 to size-1

alpha = new int[10];
Figure 11.3.1.
  • alpha is declared as an array of int
  • This statement allocates 10 slots for integers (first line are values, second line are indexes)
  • Notice that the largest index is 9 (size of 10 minus 1).

Subsection 11.3.3 SG2: Evaluate data type of statements against array

for (int i = 0; i < 10; i++)
   alpha[i] = i * 1;
  • This loop has index i go from 0 to 9 (< 10) by increments of 1.
  • Then the value i * 10 is placed into the position alpha[i].
  • All of the array indexes are within the bounds of the array (0 – 9) and all values being assigned (10-90) are valid integers and can be stored in an integer array.

Subsection 11.3.4 SG3: Trace statements, updating slots as you go

We will evaluate the first two statements:
for (int i = 0; i < 10; i++)
   alpha[i] = i * 1;
The resulting array is:
Figure 11.3.2.

Subsection 11.3.5 Practice Pages

You have attempted of activities on this page.