Arrays Overview

  • Arrays are 10-15% of the AP CSA Exam
  • The four main topics that College Board wants you to know
    • Array creation and access
    • Traversing arrays
    • Enhanced for loops for arrays
    • Developing algorithms using arrays
  • The overall purpose of arrays is to store multiple values in a single variable, instead of declaring separate variables for each value.

6.1 Array Creation and Access

  • Arrays are used to store one data type
  • Unlike Arraylists, arrays have a fixed size and cannot be changed
  • Arrays can be denoted using braces {} Below is an example of a simple array storing our scrum team names
    [Meena, Shraddha, Madhumita, Pranavi]
  • To use an array you have to use the command
    import java.util.Arrays;

Making Arrays

There are two ways to make arrays

  • using constructors
  • using pre-intiliazed arrays
dataType[] arrayName = new dataType[numberOfItems]; //Constructor
int[] arraySample = {1,3,5,7,9}; //pre-initialized arrays

Accessing Elements in Arrays

  • You can access the elements in an array using different commands
arrayName.Length //determine the size
arrayName.length - 1 //to access the last item in the array

Hack 1

How do we access the even numbers in arrayOne from above?

int[] arrayOne = {1, 3, 5, 7, 9};

for (int i = 0; i < arrayOne.length; i++) {
    if ((i + 1) % 2 == 0) {
        System.out.println(arrayOne[i]);
    }
}
3
7

Hack 2

Which of the following is FALSE about arrays

  • A. A java array is an object
  • B. Length of array can be changed after creation of array
  • C. Numerical data types of arrays are initialized to 0 to start

B is FALSE

6.2 Traversing Arrays

  • Traversing is accessing every value in the array
  • Can be done using a loop like a for loop or while loop
  • Below is an example - using a for loop, we can iterate through each fruit in the array of Strings and print it out
// Here is the array we will be working with
String[] myFruits = new String[] {"Apple", "Strawberry", "Watermelon", "Blueberry"};

for (int i = 0; i < myFruits.length; i++) {
    System.out.println("Fruit number " + i + " is " + myFruits[i]);
}
  • Can also loop through an array in reverse
for (int i = myFruits.length - 1; i >= 0 ; i--) {
    System.out.println("Fruit number " + i + " is " + myFruits[i]);
}
  • If we have a list of numbers, we could change each value in the array by a certain amount
// Here is the array we will be working with
int[] myNumbers = new int[] {1, 3, 5, 7, 9};

for (int i = 0; i < myNumbers.length; i++) {
    // add 10 to each element in the array
    myNumbers[i] += 10;
    System.out.println("New element " + i + " is " + myNumbers[i]);
}
  • We can also traverse an array using a while loop
// Here is the array we will be working with
String[] myFruits = new String[] {"Apple", "Strawberry", "Watermelon", "Blueberry"};

int i = 0; 
while (i < myFruits.length) {
    System.out.println("Fruit number " + i + " is " + myFruits[i]);
    i++;
}

Bound Errors

  • ArrayIndexOutOfBoundsException thrown, can happen when using loops to access array elements
  • In the example below instead of the condition being while the index is less than the length of the array, the condition is less than or equal too
  • This mean the loop will try to run when i = 4 (since the length of the list is 4). However since array index starts from 0, the last item in the array will have an index of 3. So, index of 4 will be out of bounds, resulting in the error.
int i = 0; 

while (i <= myFruits.length) {
    System.out.println("Fruit number " + i + " is " + myFruits[i]);
    i++;
}

Hack 3

  • Create a function that takes in a list of integers and returns the list with the integers in ascending order. Print every element in this list
  • Example
    • int[] myNumbers = new int[] {5, 3, 4, 1, 2};
    • arraySorter(myNumbers);
    • Expected Output
      • 1
      • 2
      • 3
      • 4
      • 5
public class AL {
    public static void ascending(int[] array) {
        Arrays.sort(array);
        for (int number : array) {
            System.out.println(number);
        }
    }
    public static void main(String[] args) {
        int[] myNumbers = new int[] {5, 3, 4, 1, 2};
        ascending(myNumbers);
    }
}

AL.main(null);
|   
a type with the same simple name is already defined by the static single-type-import of Arrays

|           Arrays.sort(array);
reference to Arrays is ambiguous
  both class Arrays in  and class java.util.Arrays in java.util match

Hack 4

  • Given the following code segment, which of the following will cause an infinite loop? Assume that temp is an int variable initialized to be greater than zero and that a is an array of integers.
for ( int k = 0; k < a.length; k++ )
{
   while ( a[ k ] < temp )
   {
      a[ k ] *= 2;
   }
}
  • A. The values don't matter this will always cause an infinite loop.
  • B. Whenever a includes a value that is less than or equal to zero.
  • C. Whenever a has values larger then temp.
  • D. When all values in a are larger than temp.
  • E. Whenever a includes a value equal to temp.

6.3 Enhanced for loop for Arrays

This topic was pretty short, but essentially what you need to know is about the enhanced for loop. The enhanced for loop can be used to traverse through most data structures (i.g. arrays). However, it can only traverse in a forward direction. Usually the structure is like so

for (dataType i: arrayName) {
  do something with i
}

Essentially, this code mentions how every element in the array (i) has to have something done to it. It's important to note that although there is access to the element i, but it isn't possible to change the value/set new values to element i.

We can use mutator methods on objects on the array to set the value of their instance variables. This is because i is a copy of the object reference, which means that i refers to the same object as the array element, so calling methods on i is the same as calling methods on the individual array elements themselves. For example

public class Student {
    private String name;
    
    /** Sets the name of the Student
    */
    public void setName(String name) {
      this.name = name;
    }
  
    /** Other instance variables, methods, and constructors not shown
    */
  }
  // IN ANOTHER CLASS
  /** Resets all students' names
  */
  public static void doubleArray(Student[] array, String defaultName) {
    for (Student student: array) {
      student.setName(defaultName); // Sets each student's name to a default name
    }
  }

Hack 5

In this example, each loop includes an int array and a String array. Try adding another high score and another name to the arrays and se if you can get it to run.

public class ForEachDemo
{
   public static void main(String[] args)
   {
     int[] highScores = { 10, 9, 8, 8, 11};
     String[] names = {"Jamal", "Emily", "Destiny", "Mateo", "Bailey"};
     // for each loop with an int array
     for (int value : highScores)
     {
         System.out.println( value );
     }
     // for each loop with a String array
     for (String value : names)
     {
         System.out.println(value); // this time it's a name!
     }
   }
 }

ForEachDemo.main(null);
10
9
8
8
11
Jamal
Emily
Destiny
Mateo
Bailey

Hack 6

What code would you add to the following to output the length of each String that's returned from the below method? Choose A, B, C, or D.

6.4 Developing Algorithms using Arrays

Here are some algorithms that arrays can be used for (from college board standards),

  • Minimum and Maximum of a list of elements
  • Compute the sum, average, or mode of multiple elements
  • Determine if at least one element has a property
  • Access consecutive pairs of elements
  • Determine duplicates

What to use when problem solving with arrays .length can be used to find the length of an array

  • The value at a specific index can be found with array[i], where i is the index
  • An element at index i can be replaced using array[i] = new element
  • You can iterate over an array with a for loop
    for(type element: array) {
      \\\\ code here

Computing Sums with Arrays

See the code below for a sample algorithm of how to compute the sum of elements in an array. This could be applied to finding the mean, standard deviation, or any other algorithm that requires summation.

int[] array = {5, 1, 78}; // intialize

int sum  = 0; // variable to keep track of sum

for (int number : array) { // iterates over each loop in the array
    sum += number; // the number is added to the sum
}

System.out.println(sum); //expected sum is 84, so 84 should be printed
84

Find the max

// from college board

private double findMax(double[] values) {
    double max = values[0]; // initialize max with first element of array

    for(int i=1; i<values.length; i++) { // starting with the second element, iterate over the rest of the array
        if (values[i] > max) { // if the current element is greater than the max
            max = values[i]; // set the max equal to the greatest value until that point
        }
    }

    return max; 
}

Find the amount of even numbers.

private int findEvenNumbers(int[] values) {
        int evenCount = 0; // initalize count of even numbers to zero

        for(int value: values) { // iterate over every element of array
            if(value % 2 == 0) { // use modulus operator to check if value is even
                evenCount += 1; // increment evenCount if the value is even
            }
        }
    
        return evenCount; 
    }

Hack 7

Return a left-shifted array

Ex

  • {7,9,4} --> {9,4,7}
  • {1,2,3} --> {2,3,1}
  • {0,9} --> {9,0}
  • {1} --> {1}

Hack 8

Find the number of duplicate elements in an array.

Hack 9

Use arrays to reverse a string.

Ex

  • \"hello\" --> \"olleh\"
  • \"slay\" --> \"yals\"
  • \"mom\" --> \"mom\"

Homework

Finish the FRQ part a for homework. This free response question deals with arrays.

public void addMembers(String[] names, int gradYear) {
    for (String name : names) {
        memberList.add(new MemberInfo(name, gradYear, true));
    }
}