1 of 10

Manipulations �&�Looping Through Arrays

Lessons 8.2 & 8.3

2 of 10

Simple Array Manipulations

  • Instantiating the array…

int [ ] arrayName = new int [100];

  • This array has 100 indices as indicated above, but what if the index reference does not fall between 0 and 99?

3 of 10

Range Bound Errors

  • The JVM checks the values of the index before applying a value to that element of the array.

  • A Range Bound Error occurs when the index is less than 0 or greater than the array length minus 1.

  • In the case of the previously declared array, it will have to be between 0 and 99 to be valid.

4 of 10

Range Bound Errors

  • These errors are also known as:

ArrayIndexOutOfBoundsException

5 of 10

Looping Through Arrays

  • Loops are a very useful programming tool for manipulating or checking for items in an array.

6 of 10

Looping Through Arrays

  • There are many situations where it is necessary to write a loop that iterates through an array one element at a time.

  • The following are 4 examples of using loops for arrays…

7 of 10

Looping Through Arrays

  • Sum the Elements
    • The following is code that sums the numbers in the array abc. Each time through the loop, we add a different element to the sum.

int sum;

sum = 0;

for (int i = 0; i < 500; i++) {

sum += abc[ i ];

}

8 of 10

Looping Through Arrays

  • Count the Occurrences
    • The following is code that determines how many times a number occurs in the array by comparing x to each element and incrementing count every time there is a match.

int x = 3, count = 0;

for (int i = 0; i < 500; i++) {

if (abc[ i ] == x) {

count ++;

}

}

9 of 10

Looping Through Arrays

  • Determine Presence or Absence
    • The following is code that determines whether a particular number is present or absent from an array.

int x = 3;

boolean found = false;

for (int i = 0; i < 500; i++) {

if (abc[ i ] == x) {

found = true;

break;

}

}

if (found) {

System.out.println (“Found”);

} else {

System.out.println (“Not Found”);

}

10 of 10

Looping Through Arrays

  • Determine First Location
    • The following is code that finds the first location of x in the array.

int x, location = -1;

for (int i = 0; i < 500; i++) {

if (abc[ i ] == x) {

location = i;

break;

}