# 9.1. Worked Example: Arrays - Instantiate and Alter¶

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

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;
alpha = 22;
alpha = 10;
alpha = alpha - alpha;
alpha = alpha - alpha;
alpha = alpha[alpha - 1];
alpha = alpha[alpha];
```

SG1: Set up array from 0 to size-1

```alpha = new int;
```
• `alpha` is declared as an array of ints

• This statement allocates 5 slots for integers (first line are indexes, second line are values/content):

• Notice that the largest index is 4 (size of 5 minus 1).

SG2: Evaluate data type of statements against array

```alpha = 22;
alpha = 10;
alpha = alpha - alpha;
alpha = alpha - alpha;
alpha = alpha[alpha - 1];
alpha = alpha[alpha];
```
• Each of these statements only involve integers.

• Notice that for every [ ] in the statements the result will be 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.

SG3: Trace statements, updating slots as you go

We will evaluate the first two statements:

```alpha = 22;
alpha = 10;
```

The resulting array is:

The next statement is:

```alpha = alpha - alpha;
```

Next:

```alpha = alpha - alpha;
```

For the next statement, `alpha = alpha[alpha - 1];`, first determine the value of alpha which is 2. Then look at alpha[2 - 1] which is alpha, or 12

Finally, there is a problem with the last statement: `alpha = alpha[alpha];` First determine the value of alpha which is 12. When we try to get alpha, it is out of bounds, and an `IndexOutOfBounds` exception occurs with this statement.

Practice Pages

You have attempted of activities on this page