Skip to the content.
Intro 6.1: Array 6.2: Traversing 6.3: Enhanced for 6.4: Algos

Unit 6.2 - Arrays

Unit 6 Team Teach - Arrays

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
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]);
}

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

Even Index
0
2
4
Even Index
0
2
4
Odd Index
1
3
5

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?

In the while loop, the i is defined prior to the loop while it is defined within the for loop.

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 double calculateAverage(int[] grades) {
        int sum = 0;
        for (int grade : grades) {
            sum += grade;
        }
        return (double) sum / grades.length; // Calculate average
    }

    public static void checkGrades(int[] grades) {
        double average = calculateAverage(grades);

        // Check if the average is below a certain percentage (e.g., 70%)
        if (average < 70) {
            System.out.println("Man, you guys need to study more");
        }

        // Bonus: Add points to each grade
        for (int i = 0; i < grades.length; i++) {
            grades[i] += 5; // Add 5 points to each grade
        }

        // Print new average after adding points
        average = calculateAverage(grades);
        System.out.println("New Average after adding points: " + average);
    }
}