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?

Loop 1: The first loop initializes each element of the array list with a random integer between 0 and 3. It iterates through each array index (from 0 to list.length-1) and assigns list[i] an edge-generated random integer. .nextInt(4). For loop 2: The second loop, which is each time, iterates through each element of the array list and prints it. Unlike the first for loop, this one does not deal with indexes, but goes through each element directly.________

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

In the first for loop, the elements are accessed by their index. The loop goes from the first index (0) to the last index (list.length - 1) and the elements are viewed and changed using list[i]. In the second for loop (for-each loop), the elements are used directly without an index. An element of a variable receives the value of each element of the table 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 manipulation, reducing the likelihood of common errors such as one-shots or ArrayIndexOutOfBoundsException. By removing the complexity of loop control, developers can focus on what’s important to achieve with each iteration, resulting in cleaner, more understandable code. In addition, the circular variable and its immutability prevent unwanted changes in each iteration, which contributes to the stability of the code.

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?

To calculate the array index, Math.abs is usually not needed for transfer operations, because the modulus operator (%) already ensures that the index is within a valid range. In the left shift example, the expression (i - shiftWord + words.length) % words.length cannot produce a negative index because adding words.length cancels any negative result of (i - shiftWord). In cases where index calculations may return negative values ​​that are not handled by modulus or similar normalization, wrapping the index in Math.abs can prevent an ArrayIndexOutOfBoundsException by ensuring that 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 NFLPlayerRatings {
    public static void main(String[] args) {
        // Define the number of players in the NFL team and the number of player attributes
        int numberOfPlayers = 53; // Typical roster size for an NFL team
        int numberOfAttributes = 7; // Attributes like speed, strength, agility, etc.

        // Create a 2D array to hold the initial ratings of NFL players
        double[][] initialPlayerRatings = new double[numberOfPlayers][numberOfAttributes];

        // Initialize the player ratings randomly
        Random random = new Random();
        for (int i = 0; i < numberOfPlayers; i++) {
            for (int j = 0; j < numberOfAttributes; j++) {
                // Player ratings are typically initialized with values between 60 and 99
                initialPlayerRatings[i][j] = 60 + random.nextDouble() * 40; // Random player ratings
            }
        }

        // Print out the initial player ratings array
        for (int i = 0; i < numberOfPlayers; i++) {
            for (int j = 0; j < numberOfAttributes; j++) {
                System.out.print(initialPlayerRatings[i][j] + " ");
            }
            System.out.println();
        }
    }
}
NFLPlayerRatings.main(null)
77.70289424663623 64.47765891541505 69.43498876018346 78.39207145493812 72.9893207232911 69.50350613586525 65.2358282573613 
66.61289924760693 95.93402445930232 82.19875858886843 64.27986176803086 98.48980740362998 73.04697034436623 61.28115881923128 
87.98130544458719 72.8469782400211 78.109507658544 98.63712500546704 99.07222346611677 94.24896958233438 98.56461911264438 
66.82139517462994 65.6526297650071 64.01364777265482 82.45544578951701 87.74002709219367 78.88762534218563 80.5902225672557 
63.40844661148704 70.25723536883328 72.72682525480892 69.32804628901931 91.97782470741139 80.59935443885117 67.96662427743568 
65.91961341781696 88.7381955140665 91.81203303126121 73.1711778070981 68.3090230908561 97.83276519963569 67.15957111654009 
61.41327281540593 68.61497004663116 79.25461291217654 87.23814162069587 84.49158619105816 99.62516123659796 93.95897159684097 
91.70741121895074 65.22613711296827 79.6768447185037 67.97472618391538 93.92794878257304 83.62905283693614 75.24596440467018 
70.00364714173134 80.42455588424946 84.19307750695381 82.32526512326464 81.56620416625402 66.9785167409973 79.23556966046738 
75.67947739349289 99.57310907478605 69.28455495016233 67.18104823662617 89.32353415856736 88.27204441472453 98.4910919525897 
64.86064898494726 72.07757789254937 70.83936455921328 70.57523568224528 69.35217658750473 88.81032745640698 80.45684715100757 
83.38672117224449 97.57975155630847 70.99019578533598 96.53389619949154 66.32784474061981 60.837348492451696 79.42134618077313 
73.80591876681665 65.0192422242992 76.59585366278432 87.54970745332487 90.35989294384436 66.9341863887659 61.39857128633861 
65.48176548751621 95.2084598224169 63.86687381419542 86.34541459323697 82.86675985163919 86.85420462930385 63.232992678838464 
90.61135584939052 93.05074302837629 81.3560795141062 82.5836807207616 98.63998257142883 91.41876020266614 91.73024016447764 
70.3467829546576 73.09836409959615 97.59921328711576 60.08790019166992 70.69214377059065 78.37470129438587 94.21230485377063 
99.73308075414063 71.55046658625574 88.34558224869858 64.10225030912147 76.513489429789 82.19810169592292 67.33495670224711 
83.50077390661511 87.03804276390437 80.45292571352945 84.63225773552794 90.32721298951179 95.94487041941373 69.40929457553105 
70.63242044530779 94.83835473343527 75.22395656269015 69.77284591997059 66.6058563768888 74.09896114355554 85.66887411110338 
86.23878221850505 60.30173772227772 72.25174333951907 93.8523962392822 84.99002297135081 96.03329523313369 75.32335205408988 
87.59106331274197 84.27446987264261 60.58910612069561 82.31076791177597 78.68411550382794 71.15342218300799 95.25968776107973 
93.55030184544225 63.78249545188534 94.89599703397326 89.46400773665906 82.87919155927037 72.56394821439591 71.1272140802601 
92.90585943360861 91.85764373028519 66.96056463596307 80.7202393224915 60.88532362144066 62.326936499443754 66.00540469957741 
63.5560554650142 81.33588917406999 67.83703618649048 97.935176309545 69.6566818828363 82.35310266691663 94.98498997415531 
64.50623453619497 78.83085415623444 65.42591243308705 62.46316830959629 62.05150318852298 74.8538883469719 72.27722262005132 
68.62423087100964 99.62619499973013 81.33627489443084 92.16544691832524 87.62752702085899 86.66057547239467 73.81835391795283 
71.6941911984834 89.73943405584603 70.85826872642072 76.26123630073843 60.62249081191452 83.11795221685462 71.64895133229068 
89.98695558496867 74.86334973338447 62.41969943848502 75.32459752079981 69.25363581714615 81.80363630666942 63.82524901095027 
75.05871680163014 70.03427521375292 93.27370972826563 66.5865618835369 92.32837376146381 77.2005760622798 87.94045157405306 
67.95810371621238 65.82907507413739 60.19602968220052 97.59269995908727 91.38101676941594 99.79292623849665 78.41531850243909 
80.7333921744457 87.04754381181978 65.69076032901347 74.8898686060939 92.08804049725595 89.48073071840977 69.61927912824008 
80.51223459403755 98.08446432627184 88.52220254964004 72.24453519392533 60.91478485164118 66.05402634725874 88.12867557920335 
98.9934069317457 94.25098655563319 68.84992935675326 91.63563350943147 85.25502752920902 90.51038496868162 96.7734451271455 
62.654434621104464 64.67445245969306 91.63120226325745 95.1442559556105 67.52692652060972 88.19113673569696 86.55727636416759 
88.54639628442548 88.2694407770656 77.29514588929389 76.51888685804298 71.72661164064314 84.19587651752883 87.04428285293565 
73.19981745570828 82.31724849454062 95.9173818876574 62.705688101664634 86.08582274485927 82.00110571895266 87.17394512330995 
78.45572954427394 75.17247898211126 80.43099647599422 87.96104202180877 87.39233721925729 71.34320563735152 60.162068894250126 
76.67228172835216 69.18424976523946 79.11106956524105 61.05026370406402 79.48681114425962 95.00194873683208 95.05077458657934 
99.01558806250077 91.98804534867456 78.94535954924235 80.13007817047915 66.76419169357567 81.00812296682139 91.00372992125708 
95.28267083365222 73.00856863134852 63.95026631406428 68.6533943694651 86.947370764874 61.92048230022155 88.3490690486224 
62.51944665466641 72.93129623855685 95.99656585336118 86.18652453594322 66.09766632597605 88.83751140363523 63.21182983659941 
95.48943795557358 90.3533389259136 91.43040403941069 63.2816333686581 65.9916640334187 91.08394651658004 77.69493878557341 
98.04799961768896 76.15242963039447 80.25298999938596 86.97867153468795 97.45143968568068 85.5798195733611 92.07253855660355 
68.48826046151217 75.244798970661 89.91629944587609 70.4324081483255 97.54502648369484 87.55091122648096 94.5009867258793 
76.34417598322182 71.3869037829011 62.56119762176055 78.63116868167577 82.38856210742037 88.93694850563382 81.11763508191783 
84.00339539580631 65.7250098075487 98.84139024500493 75.61583485248494 88.92227467278322 92.04262346937129 86.21301280218547 
98.61229291813507 64.12293333075024 79.9019186520737 60.898464861316334 92.71417957651829 66.56088276681527 68.23716582286994 
88.72092520010744 69.77535113308384 94.28087579202105 79.35941041887553 92.03234156112691 60.117576259294914 98.4841342323484 
75.62057475076394 97.04229169889797 81.44128317481164 68.17115209375746 89.9693500123596 62.773312638180926 62.285446705955174 
68.24506507044453 88.94990805503252 70.12537599037192 96.34155239853644 83.71843172063117 61.26476984299636 79.41497102339427 
81.6218731889856 60.674048711930844 95.84347135420636 80.88710154624172 72.42761915527555 78.88824553026873 60.429012834992434 
65.0812937075862 62.257835623515746 61.53292407665588 75.01434037322917 68.56553058090249 62.24521568823214 64.13041491600157 
94.0314625782089 85.43484253778712 82.40034048051592 67.94303485716911 87.01610192592835 76.10409406888351 81.8911397147109 

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 PrimeJerseyNumbers {
    public static void main(String[] args) {
        // Array of jersey numbers in an NFL team
        int[] jerseyNumbers = {12, 3, 80, 19, 55, 88, 7, 33, 84, 58, 9, 28};

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

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

    // Helper method to check if a jersey 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;
    }
}

PrimeJerseyNumbers.main(null)
Prime jersey numbers (identified using a for loop):
3
19
7

Prime jersey numbers (identified using a while loop):
3
19
7

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!

EXTRA CREDIT WORK

Extra Credit NFL Code

public class NFLPlayerStats {
    public static void main(String[] args) {
        // Define the number of players on an NFL team
        int numberOfPlayers = 53;

        // Create arrays to store player information
        String[] playerNames = new String[numberOfPlayers];
        int[] jerseyNumbers = new int[numberOfPlayers];
        double[] yardsGained = new double[numberOfPlayers];
        int[] touchdowns = new int[numberOfPlayers];

        // Simulate player data entry
        playerNames[0] = "Tom Brady";
        jerseyNumbers[0] = 12;
        yardsGained[0] = 4567.5;
        touchdowns[0] = 40;

        playerNames[1] = "Aaron Donald";
        jerseyNumbers[1] = 99;
        yardsGained[1] = 0;
        touchdowns[1] = 0;

        // Simulate more player data...

        // Using a for loop to display player stats
        System.out.println("NFL Player Stats:");
        for (int i = 0; i < numberOfPlayers; i++) {
            System.out.println("Player Name: " + playerNames[i]);
            System.out.println("Jersey Number: " + jerseyNumbers[i]);
            System.out.println("Yards Gained: " + yardsGained[i]);
            System.out.println("Touchdowns: " + touchdowns[i]);
            System.out.println();
        }

        // BONUS: Using a while loop to display player stats
        System.out.println("NFL Player Stats (while loop):");
        int index = 0;
        while (index < numberOfPlayers) {
            System.out.println("Player Name: " + playerNames[index]);
            System.out.println("Jersey Number: " + jerseyNumbers[index]);
            System.out.println("Yards Gained: " + yardsGained[index]);
            System.out.println("Touchdowns: " + touchdowns[index]);
            System.out.println();
            index++;
        }
    }
}
NFLPlayerStats.main(null)
NFL Player Stats:
Player Name: Tom Brady
Jersey Number: 12
Yards Gained: 4567.5
Touchdowns: 40

Player Name: Aaron Donald
Jersey Number: 99
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

NFL Player Stats (while loop):
Player Name: Tom Brady
Jersey Number: 12
Yards Gained: 4567.5
Touchdowns: 40

Player Name: Aaron Donald
Jersey Number: 99
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Player Name: null
Jersey Number: 0
Yards Gained: 0.0
Touchdowns: 0

Extra Credit NBA Code

import java.util.Random;

public class NBATeamStatistics {
    public static void main(String[] args) {
        // Define the number of NBA teams
        int numberOfTeams = 5;

        // Create arrays to store team information
        String[] teamNames = {"Lakers", "Warriors", "Celtics", "Rockets", "Heat"};
        int[] totalPoints = new int[numberOfTeams];
        int[] totalAssists = new int[numberOfTeams];

        // Simulate player data and calculate team statistics
        Random random = new Random();
        for (int i = 0; i < numberOfTeams; i++) {
            int playersInTeam = random.nextInt(10) + 5; // Simulate 5-14 players per team
            for (int j = 0; j < playersInTeam; j++) {
                int pointsScored = random.nextInt(30) + 10; // Simulate 10-39 points per player
                int assists = random.nextInt(15) + 5; // Simulate 5-19 assists per player
                totalPoints[i] += pointsScored;
                totalAssists[i] += assists;
            }
        }

        // Display team statistics using a for loop
        System.out.println("NBA Team Statistics:");
        for (int i = 0; i < numberOfTeams; i++) {
            System.out.println("Team: " + teamNames[i]);
            System.out.println("Total Points: " + totalPoints[i]);
            System.out.println("Total Assists: " + totalAssists[i]);
            System.out.println();
        }
    }
}
NBATeamStatistics.main(null)
NBA Team Statistics:
Team: Lakers
Total Points: 292
Total Assists: 170

Team: Warriors
Total Points: 232
Total Assists: 108

Team: Celtics
Total Points: 221
Total Assists: 131

Team: Rockets
Total Points: 177
Total Assists: 80

Team: Heat
Total Points: 290
Total Assists: 155