Arrays

8. Using a Variable as an Index


Answer:

stuff[0] has 23
stuff[1] has 38
stuff[2] has 14
stuff[3] has 0
stuff[4] has 0

Using a Variable as an Index

The index of an array is always an integer type. It can be an integer literal, or an expression that evaluates to an integer. For example, the following are legal:

int values[] = new int[7];
int index;

values[ 6 ] = 42;           // literal

index  = 0;
values[ index ] = 71;       // put 71 into cell 0

index  = 5;
values[ index ] = 23;       // put 23 into cell 5

index  = 3;
values[ 2+2 ] = values[ index-3 ];  // same as values[ 4 ] = values[ 0 ];          

Question 8:

Given the above declarations, is the following legal?

    index = 4; values[ index+2 ] = values[ index-1 ];