By: (J)onathan, (I)an, (T)arun, (S)rijan

Topic 6.2 - Traversing Array (1D)

Using iteration statements (standard for loops and while loops) to access each element in an array.

The Classic For Loop

  • An array in java is indexed from n1 to the number of elements n2.

Review on what a for loop is?

  • init: The init expression is used to initialize a variable (executed once)
  • condition: The loop executes the condition statement every iteration.
  • incr/decr: The increment/decrement statement applied to the variables which updates the initial expression. forLoopExample

Here’s some basic code (boring stuff):

import java.util.Random;

public class RandomArray {
    public static void main(String[] args){
    int [] list = new int[6];
    Random rand = new Random(); 

    // FOR LOOP 1
    for (int i = 0; i < list.length; i++){
        list[i] = rand.nextInt(4);
    }

    // FOR LOOP 2
   for(int element: list){
        System.out.println(element);
    }

   }

   }

  RandomArray.main(null);
0
0
1
2
2
2

forLoopGif

For Loop: Accessing List Elements

Popcorn hack question

Which part of the following code would I want to change if I wanted to access all odd indices of the list.

// EVEN
int[] list = {0, 1, 2, 3, 4, 5};
System.out.println("Even Index");
for(int index = 0; index < list.length; index+=2){
    System.out.println(list[index]);
}
Even Index
0
2
4

Standard While Loop

Does the following loop accomplish traversing the array?

int [] list = new int[5];
int index = 0; 

while (index < list.length) 
{
    // Do something
    index ++; 
}

System.out.println("New index: " + index);
New index: 5

Popcorn hack question:

This while loop and the for loop we used earlier accomplish the same task. The main difference is that after the loop is completed, the variable ‘index’ in the while loop will still exist. The variable ‘i’ in the for loop will not. Why?

Bounds Errors

When traversing an array, we need to be careful with the indices to avoid an ArrayIndexOutOfBoundsException being thrown.

**ATTENTION: MOST COMMON MISTAKE: **

  1. What is wrong with the for loop and while loop below? Why does this produce an ArrayIndexOutOfBoundsException error? The first index is 0 making the equation invalid. You must change the signs or add a -1

Off by One Error : missing the first or last element of an array when trying to traverse

Developing Methods Using Arrays

Reviewing common methods asked on AP Exams FRQs

Average Value

Popcorn Hack:

Create/complete the code in order to return the average grade of all grades in the list of grades.

Homework:

Have the code print “Man, you guys need to study more” if the grades are beneath a certain percentage.

Bonus: Have the code iterate through the list and add some points to each grade because you’re a very generous grader.

public class GradeAverage {
    public static void main(String[] args) {
        /* grades out of 100 */
        int[] grades = {90, 50, 70, 20, 80, 97};
        int sum = 0;
        double average;
        
        for (int i = 0; i<grades.length;i++) {
            sum += grades[i]; 
        }
       
        average = (double) sum / grades.length; /* missing code */
        
        System.out.println("The average of the grades is: " + average);
    }
}

GradeAverage.main(null);