Hello! wget this notebook RIGHT NOW

(Find the link in ‘coding’ on SLACK)

Topic 6.1 - Array Creation and Access (Sreeja)

Vocabulary

  • Array: a data strucutre used to implement a collection of object referance data
  • Element: a single value within an array
  • Index of an element: position of an element in the array (In java, the first element of an array is at index 0)
  • Length of an array: number of elements in the array

Declaring an Array

Defines the array variable, specifying its data type and name.

// Syntax: dataType[] arrayName;
int[] numbers; // Declare an integer array
String[] names; // Declare a string array

Creating an Array

Gives memory for the array and specifies its size.

// Syntax: arrayName = new dataType[size];
numbers = new int[5]; // Create an integer array with 5 elements
names = new String[3]; // Create a string array with 3 elements
|   numbers = new int[5];

cannot find symbol

  symbol:   variable numbers

Initializing an Array

Populates the array with initial values.

// Syntax: arrayName = new dataType[size];
numbers = new int[5]; // Create an integer array with 5 elements
names = new String[3]; // Create a string array with 3 elements
|   numbers = new int[5];

cannot find symbol

  symbol:   variable numbers

Accessing Array Elements

Retrieves a specific element’s value from the array using its index.

int[] numbers = {10, 20, 30, 40, 50};
int element = numbers[2]; // Access the third element (30) using index 2
System.out.println(element); // Output: 30

30

Array Length

Obtains and displays the number of elements in the array.

int[] numbers = {10, 20, 30, 40, 50};
int length = numbers.length; // Get the length of the array
System.out.println("Array length: " + length); // Output: Array length: 5
Array length: 5

Modifying Array Elements

Updates the value of a specific element in the array.

int[] numbers = {10, 20, 30, 40, 50};
numbers[2] = 35; // Change the third element to 35
System.out.println(numbers[2]);
35

Iterating Through an Array

Loops through the array, printing each element.

int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]+5);
}
15
25
35
45
55

Enhanced For Loop (For-each)

Iterates through the array using a simplified loop structure, printing each element.

int[] numbers = {10, 20, 30, 40, 50};
for (int number : numbers) {
    System.out.println(number);
}
10
20
30
40
50

Topic 6.2 - Traversing Array (1D) (Tanisha)

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

Standard For Loop

  • An array in java is indexed from 0 to the number of elements - 1.

Review on For Loops

  • init: The init expression is used for initializing a variable, and it is executed only once.
  • condition: It executes the condition statement for every iteration
  • incr/decr: It is the increment or decrement statement applied to the variable, updates the initial expression.

image

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);
*/

Class Discussion-Take Notes, these will count for points in your hacks!

  1. What do the for loops accomplish?

For Loop 1: The first for loop initializes each element of the array list with a random integer from 0 to 3. It iterates through each index of the array (from 0 to list.length - 1) and assigns a random integer generated by rand.nextInt(4) to list[i]. For Loop 2: The second for loop, which is a for-each loop, iterates through each element of the array list and prints it out. Unlike the first for loop, it doesn’t deal with indexes but rather goes through each element directly. ________

  1. What is the difference between how elements of the array list are accessed?

In the first for loop, elements are accessed via their index. The loop runs from the first index (0) to the last index (list.length - 1), and elements are accessed and modified using list[i]. In the second for loop (for-each loop), elements are accessed directly without the use of an index. The variable element takes on the value of each element in the array list sequentially from the first to the last. ________

  1. BONUS: When the array list of ints was first created, what was each int in the list initialized to?

When an array of ints is first created in Java, each int in the array is automatically initialized to 0. This is a default value for integer arrays in Java. _________

download

For loop : Accessing Some Elements of a List

Class Discussion-Take Notes, these will count for points in your hacks!

  1. If I only wanted to access the elements at even indices of the list (0, 2, 4), what could I change in the statement below to accomplish that?

  2. What about odd?

// 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


Odd Index
1
3
5

Note: These are NOT traversals, even though these are for loops. This is because not every element in the array is accessed.

Standard While Loop

  1. Does the following loop accomplish traversing the array?

No it doesn’t, as there is no accessing of the elements within the array.

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

while (index < list.length) 
{

    index ++; 
}
  1. 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?

Due to the fact i is declared within the for loop, it is limited to that loop. When the loop is over i goes out of scope and cannot be accessed. In the while loop, index is declared outside of the loop, so it will remain in scope and still be accessible after the loop completes. ____________

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? Java starts at zero, so i cannot be equal to list.length, it has to be less.
for(int i = 0; i <= list.length; i ++)
int index = 0; 
while (index <= list.length)

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

[0, 1, 2, 3, 4]
// This won't access the last element in the list
for(int i = 0; i < list.length - 1; i ++)
// This won't access the first element in the list
int index = 1; 
while (index <= list.length)

Developing Methods Using Arrays

Reviewing common methods asked on AP Exam FRQs

Average Value

Complete the popcorn hack below in order to return the average value of the elements in the list numbers.

public class ArrayAverage {
    public static void main(String[] args) {
        int[] numbers = {5, 10, 15, 20, 25};
        int sum = 0;
        double average;
        
        for (int i = 0; i < numbers.length; i++) {
            sum += numbers[i]; 
        }
        
       
        average = (double) sum/numbers.length; /* missing code */
        
        System.out.println("The average of the numbers is: " + average);
    }
}

ArrayAverage.main(null);
The average of the numbers is: 15.0

6.3 Enhanced for loop for Arrays (Vivian)

  • the enhanced for loop is also known as the “for each” loop
  • provides a simplified way to loop through elements in an array, collection, or other iterable data structures.
//syntax for enhanced for loop
for (dataType element : array) {
    // code to process 'element'
}
  • the data type in the loop must match the array’s element data type.
//array of int matches element int
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
    System.out.println(num);
}
1
2
3
4
5

Comparing a regular for loop with the enhanced for loop

Popcorn Hack: Rewrite this code to use an enhanced for loop instead. make comments explaining what you added/changed

import java.util.List;
import java.util.Map;
import java.util.LinkedHashMap;

class Quote {
    private Map<String, String> quoteEmotions;

    public Quote(List<String> quotes, List<String> emotions) {
        // Ensure both lists have the same size or handle size differences appropriately
        this.quoteEmotions = new LinkedHashMap<>(); // LinkedHashMap will maintain the order of insertion
        for (int i = 0; i < quotes.size(); i++) {
            this.quoteEmotions.put(quotes.get(i), emotions.get(i));
        }
    }

    public void printQuotesWithEmotions() {
        // Enhanced for loop (for-each) to iterate over the map's entries
        for (Map.Entry<String, String> entry : quoteEmotions.entrySet()) {
            String quote = entry.getKey(); // Retrieve the quote
            String emotion = entry.getValue(); // Retrieve the corresponding emotion

            System.out.println("Quote: \"" + quote + "\"");
            System.out.println("Emotion: " + emotion);
            System.out.println("---------------------------");
        }
    }

    public static void main(String[] args) {
        List<String> quotes = List.of(
            "Success is not final, failure is not fatal: It is the courage to continue that counts.",
            "The only way to do great work is to love what you do.",
            "The best way to predict the future is to create it."
        );

        List<String> emotions = List.of(
            "Courageous",
            "Passionate",
            "Innovative"
        );

        Quote quotePrinter = new Quote(quotes, emotions);
        quotePrinter.printQuotesWithEmotions();
    }
}

Quote.main(null);

Quote: "Success is not final, failure is not fatal: It is the courage to continue that counts."
Emotion: Courageous
---------------------------
Quote: "The only way to do great work is to love what you do."
Emotion: Passionate
---------------------------
Quote: "The best way to predict the future is to create it."
Emotion: Innovative
---------------------------

What are some of the benefits of using an enhanced for loop in this case versus a regular for loop?

Its concise syntax eliminates the need for manual index handling, thereby reducing the likelihood of common mistakes like off-by-one errors or ArrayIndexOutOfBoundsException. By abstracting away the complexities of loop control, enhanced for loops allow developers to focus on the essence of what they’re trying to accomplish with each iteration, leading to cleaner, more understandable code. Additionally, the loop variable’s immutability within each iteration prevents inadvertent modifications, contributing to code stability.

Limitations to enhanced for loop

  • it does not provide access to the index of the current element.
    • This means you cannot easily determine the position of the element in the array or collection.
    • But when you want to search for a specific element in a collection and you don’t necessarily need to access the index
    • If you need to work with indices, you should use a traditional for loop instead.
  • read-only access to elements.
    • You cannot modify the elements within the loop
    • Thus, when you need to modify a collection based on a condition. You should use a regular for loop

For the next two code blocks, decide whether or not its better to use a regular for loop or an enhanced one, explain why. write the code for them

  1. Searching for an Element in an ArrayList

In this case, an enhanced for loop is more suitable because you’re simply iterating through each element in the list without the need to know the element’s index. You’re checking each element against a condition (whether the element equals searchName), and there’s no need to manipulate the list structure itself.

ArrayList<String> names = new ArrayList<>();
String searchName = "Vivian";
boolean found = false;

//code goes here
for (String name : names) {
    if (name.equals(searchName)) {
        found = true;
        break; // Exit the loop early since we've found the name
    }
}

if (found) {
    System.out.println(searchName + " was found in the list.");
} else {
    System.out.println(searchName + " was not found in the list.");
}
Vivian was not found in the list.
  1. Removing Even Numbers from an ArrayList

For this task, a traditional for loop is necessary because you’re modifying the list (removing elements) while iterating through it. Using an enhanced for loop can result in ConcurrentModificationException if you try to remove items while iterating through the collection. Additionally, when you remove an item from an ArrayList, the indexes of subsequent items change, which can cause issues with an enhanced for loop.

ArrayList<Integer> numbers = new ArrayList<>();

//code goes here
for (int i = 0; i < numbers.size(); i++) {
    if (numbers.get(i) % 2 == 0) { // Check if the number is even
        numbers.remove(i);
        i--; // Decrement the index since we removed an element
    }
}

6.4: Developing Algorithms Using Arrays (Isabelle)

How to identify the maximum or minimum value in an array

It is a common task to determine what the largest or smallest value stored is inside an array. In order to do this, we need a method that can take a parameter of an array of primitve values (int or double) and return the item that is at the appropriate extreme.

Inside the method a local variable is needed to store the current max or min value that will be compared against all the values in the array. You can assign the current value to be either the opposite extreme or the first item you would be looking at.

You can use either a standard for loop or an enhanced for loop to determine the max or min. Assign the temporary variable a starting value based on what extreme you are searching for.

Inside the for loop, compare the current value against the local variable; if the current value is better, assign it to the temporary variable. When the loop is over, the local variable will contain the appropriate value and is still available and within scope and can be returned from the method.

Find max in an array of double values

private double findMax(double [] values) {
    double max = values[0];

    for (int index = 1; index < values.length; index++) {
        if (values[index] > max) {
            max = values[index];
        }
    }
    return max;
}

Find min in an array of int values

private int findMin(int [] values) {
    int min = Integer.MAX_VALUE;

    for (int currentValue: values) {
        if (currentValue < min) {
            min = currentValue;
        }
    }
    return min;
}

Let’s Practice!

Popcorn hack #1

// What needs to be changed to find the index of the max value? (write correct code in cell below)
private int findMaxIndex(double[] values) {
    int maxIndex = 0; // Store the index of the max value
    double max = values[0]; // Store the max value

    for (int index = 1; index < values.length; index++) {
        if (values[index] > max) { // If a larger value is found
            max = values[index]; // Update the max value
            maxIndex = index; // Update the index of the max value
        }
    }
    return maxIndex; // Return the index of the max value
}

How to calculate the average value from objects in an array

It is a common task to determine what is the average value returned from items stored inside an array. In order to do this, we need a method that can take a parameter of an array of Objects (DebugDuck) and calculate and return the average value that each instance of DebugDuck returns from the method.

Inside the method; a local double variable is needed to store the accumulated values. Then we use a for loop to traverse the array and add the current total to the variable. After accumulating all the values we need to divide the total by the number of items stored in the array.

Using a standard for loop

private double calculateAverage(DebugDuck [] ducks) {
    double average = 0.0;

    for (int index = 0; index < ducks.length; index++) {
        average += ducks[index].getQuestionCount();
    }
    average = average / ducks.length;

    return average;
}

Using a standard enhanced loop

private double calculateAverage(DebugDuck [] ducks) {
    double average = 0.0;

    for (DebugDuck currentDuck: ducks) {
        average += currentDuck.getQuestionCount();
    }
    average = average / ducks.length;

    return average;
}

Does the order of accumulation matter? In this specific case, the order of accumulation does not matter. We’re summing up the question counts of the DebugDuck objects, and addition is commutative (i.e., a + b is the same as b + a). Whether we start accumulating from the start of the array or the end, we’ll end up with the same total sum. The average, which is this sum divided by the number of DebugDuck objects, will also be the same regardless of the order in which we accumulate the question counts.

Can you declare the variable inside the loop?

If referring to the average variable, it cannot be declared inside the loop if its value is intended to be returned from the method. Variables declared within a loop are confined to that loop’s scope, making them inaccessible outside of it. Declaring average inside the loop would prevent it from being accessible at the return statement, due to scope limitations.

Shfiting Array contents to the right

The contents of an array often need to be shifted as part of a solution to using the data inside.

We need to know how much to shift the array by. This will need to be an int obviously.

In order to move the contents we next need to make an empty array of the same size and then iterate over the original array and properly copy the values to the adjusted index in the new array.

We then need to assign the new array back into the original variable.

I regualr one that increments an index variable by one, and the condition that the loop still goes is index < numbers.length.

What kind of for loop should we use? Why?

A regular for loop, as we need to know index.

int [] numbers = {1,2,3,4,5};
int [] shifted = new int [numbers.length];
int shift = 8;
for (int index = 0; index < numbers.length; index++) {
    shifted [Math.abs((index + shift) % numbers.length)] = numbers[index];
}
numbers = shifted;
for (int num : numbers) {
    System.out.print(num + " ");
}
3 4 5 1 2 

Why are we using the % operator?

Popcorn hack #2

How would we code a left shift? Write a left shift using the variables below

String[] words = {"alpha", "beta", "gamma", "delta"};
int shiftWord = 2;


String[] shiftedWords = new String[words.length];

for (int i = 0; i < words.length; i++) {
    int newLocation = (i - shiftWord + words.length) % words.length;
    shiftedWords[newLocation] = words[i];
}

System.arraycopy(shiftedWords, 0, words, 0, words.length);

for (String word : words) {
    System.out.println(word);
}

gamma
delta
alpha
beta

Why should the array index be wrapped in a call to Math.abs?

Using Math.abs in array index calculations is generally unnecessary in the context of shifting operations, as the modulo operator (%) already ensures the index remains within the valid range. In the left shift example, the expression (i - shiftWord + words.length) % words.length cannot yield a negative index because adding words.length negates the potential negative result from (i - shiftWord). However, in cases where index calculations might result in negative values not subjected to modulo or similar normalization, wrapping the index in Math.abs could prevent ArrayIndexOutOfBoundsException by ensuring the index is a non-negative integer.

Hacks

Scoring Guidelines:

  • 0.2 for completeing each of the sub-unit hacks mentioned below.
    • FRQ/PopCorn hacks will be graded AP Style
  • 0.1 for having organized notebook with note taking when appropriate.
  • Extra 0.1 for going above expectations for the hacks (being creative!)

6.1 HACK 1 FRQ (<5 min)

Follow the steps in the lesson to just make an array that has some relation to your project. Feel free to use the code examples we provided in your hack if you would like.

import java.util.Random;

public class NeuralNetwork {
    public static void main(String[] args) {
        // Define the number of neurons in the layer and the number of input features
        int numberOfNeurons = 10;
        int numberOfInputs = 5;

        // Create a 2D array to hold the initial weights of the neural network's layer
        // Each neuron has a set of weights corresponding to the input features
        double[][] initialWeights = new double[numberOfNeurons][numberOfInputs];

        // Initialize the weights randomly
        Random random = new Random();
        for (int i = 0; i < numberOfNeurons; i++) {
            for (int j = 0; j < numberOfInputs; j++) {
                // Weights are typically initialized to small random values
                initialWeights[i][j] = random.nextGaussian() * 0.1; // Small random weights using Gaussian distribution
            }
        }

        // Print out the initial weights array
        for (int i = 0; i < numberOfNeurons; i++) {
            for (int j = 0; j < numberOfInputs; j++) {
                System.out.print(initialWeights[i][j] + " ");
            }
            System.out.println();
        }
    }
}

6.2 HACK 1 FRQ (<10 min)

Prime Numbers in an Array (5-10 min)

Create a loop to identify and print the prime numbers from an array of integers. Your loop MUST traverse through the given list. Some things to consider:

BONUS: Do this with a for loop AND a while loop

  • Understand prime numbers and how to check for primality.
  • Implement a loop and conditional statements to iterate through the array.
  • Consider data storage (either displaying prime numbers immediately or storing them for later display)
public class PrimeNumbersArray {
    public static void main(String[] args) {
        // Array of integers
        int[] numbers = {2, 9, 3, 8, 11, 27, 17, 19, 15, 20, 23, 29};

        // Using a for loop to identify and print prime numbers
        System.out.println("Prime numbers (identified using a for loop):");
        for (int number : numbers) {
            if (isPrime(number)) {
                System.out.println(number);
            }
        }

        // BONUS: Using a while loop to identify and print prime numbers
        System.out.println("\nPrime numbers (identified using a while loop):");
        int index = 0;
        while (index < numbers.length) {
            if (isPrime(numbers[index])) {
                System.out.println(numbers[index]);
            }
            index++;
        }
    }

    // Helper method to check if a number is prime
    public static boolean isPrime(int number) {
        if (number <= 1) {
            return false; // numbers less than or equal to 1 are not prime
        }
        for (int i = 2; i <= Math.sqrt(number); i++) {
            if (number % i == 0) {
                return false; // number is divisible by some number other than 1 and itself
            }
        }
        return true;
    }
}

PrimeNumbersArray.main(null);

Prime numbers (identified using a for loop):
2
3
11
17
19
23
29

Prime numbers (identified using a while loop):
2
3
11
17
19
23
29

6.2 HACK 2 MCQ (<5 min)

Multiple Choice Questions

Do NOT Run the code cells. Try to do this on your own.

  1. What will be displayed as the output?
String [] list = {"red", "yellow", "blue"}; 
for (int i = 0; i < list.length; i++)
{
    System.out.print(list[i].length()+ "-" )
}
  • A. red-yellow-blue
  • B. 3-3-3-
  • C. 3-6-4-
  • D. 3-6-
  • E. 3-6-4

Write why you chose that answer!

we traverse therough the array, get the lenght of each word and then print a hyphen after the lenght fo each word. 3-6-4- seems like what would happen. ________

  1. The code below is meant to display every other number in the list numbers. Which of the following should replace the missing code in order to do this?
int [] numbers = {3, -4, 6, -7, 2}; 
for(/*missing code*/)
{
    System.out.println(numbers[i]);
}
  • A. int i = 0; i < numbers.length/2; i++
  • B. int i = 1; i < numbers.length; i++
  • C. int i = 1; i < numbers.length; i+=2
  • D. int i = 0; i < numbers.length; i++
  • E. int i = 0; i < numbers.length; i+=2

Write why you chose that answer!

The chosen answer would print out all of the even indexed numbers (0, 2, 4). ________

  1. (This one is a little hard) Which of the following would fix the code so that the elements in arr are reversed. Hint: try creating a list in your head and trace the code to see if the code accomplishes its goal.
public static void reverseArray(double [] arr)
{
    for(int = 0; i< arr.length; i++)
    {
        double temp = arr[i];
        arr[i] = arr[arr.length-1-i];
        arr[arr.length-1-i] = temp; 
    }
}
  • A. Change loop condition to: i < arr.length - 1
  • B. Change loop condition to: i < arr.length/2
  • C. Change loop condition to: i < arr.length/2 - 1

In case you are having trouble with question 3 the answer is B. Write about why!

The method does this by swapping elements symmetrically around the array’s midpoint. If the loop runs until i < arr.length, it will effectively swap each element twice: once on the way up to the midpoint and once on the way past the midpoint, resulting in the original array order. By stopping the loop at i < arr.length/2, each element is swapped only once, correctly reversing the array. Options A and C would either swap too few elements or cause an off-by-one error, respectively, leading to incorrect results. ___________

6.3 HACK

  • Just finish the popcorn hacks throughout the lesson!

6.4 HACK

  • Just finish the 2 popcorn hacks in the lesson!