RIGHT NOW
(Find the link in ‘coding’ on SLACK)
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
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
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
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
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
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
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]);
}
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);
}
Using iteration statements (standard for loops and while loops) to access each element in an array.
Review on For Loops
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!
Class Discussion-Take Notes, these will count for points in your hacks!
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?
To access elements at even indices, you can change the increment statement in the for loop to index += 2 starting from index 0.
What about odd?
To access elements at odd indices, you can start the index from 1 and then use index += 2.
// 4
for(int index = 0; index < list.length; index += 2){
System.out.println(list[index]);
}
// 5
for(int index = 1; 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++){
System.out.println(list[index]);
}
// ODD
int[] list = {0, 1, 2, 3, 4, 5};
System.out.println("Odd Index");
for(int index = 0; index < list.length; index++){
System.out.println(list[index]);
}
Note: These are NOT traversals, even though these are for loops. This is because not every element in the array is accessed.
int [] list = new int[5];
int index = 0;
while (index < list.length)
{
// Do something
index ++;
}
The main difference between the two loops in terms of variable scope is that the index variable in the while loop is declared outside of the loop, so it exists after the loop is completed. In contrast, the variable i in the for loop is declared within the loop, so its scope is limited to the loop, and it does not exist outside of the loop. This is a fundamental aspect of how for loops are designed in Java, to limit the scope of the loop variable to the loop itself.
When traversing an array, we need to be careful with the indices to avoid an ArrayIndexOutOfBoundsException being thrown.
ATTENTION: MOST COMMON MISTAKE:
The issue with both the for loop and the while loop is that they use <= in the condition, which means the loop will continue as long as the index is less than or equal to the length of the list. However, arrays in Java are zero-indexed, so the valid indices range from 0 to list.length - 1. When the index equals list.length, it is out of bounds, and trying to access an element at that index will result in an ArrayIndexOutOfBoundsException.
The fix is:
for(int i = 0; i < list.length; i++) {
// Do something
}
int index = 0;
while (index < list.length) {
// Do something
index++;
}
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)
Reviewing common methods asked on AP Exam FRQs
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;
System.out.println("The average of the numbers is: " + average);
}
}
ArrayAverage.main(null);
The average of the numbers is: 15.0
//syntax for enhanced for loop
for (dataType element : array) {
// code to process 'element'
}
//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
Popcorn Hack: Rewrite this code to use an enhanced for loop instead. make comments explaining what you added/changed
import java.util.List;
class Quote {
private List<String> quotes;
private List<String> emotions;
public Quote(List<String> quotes, List<String> emotions) {
this.quotes = quotes;
this.emotions = emotions;
}
public void printQuotesWithEmotions() {
for (int i = 0; i < Math.min(quotes.size(), emotions.size()); i++) {
String quote = quotes.get(i);
String emotion = emotions.get(i);
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?
In this case, using an enhanced for loop doesn’t bring many benefits because we need to iterate over two lists in parallel, and an enhanced for loop is not suitable for this purpose. Some in general are:
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
ArrayList<String> names = new ArrayList<>();
String searchName = "Vivian";
//code goes here
for () {
}
For the first code block, since we are searching for a specific name in the list, a regular for loop is more suitable because it allows us to break out of the loop once the name is found, which can be more efficient.
ArrayList<String> names = new ArrayList<>();
String searchName = "Vivian";
for (int i = 0; i < names.size(); i++) {
if (names.get(i).equals(searchName)) {
System.out.println("Found " + searchName);
break;
}
}
ArrayList<Integer> numbers = new ArrayList<>();
//code goes here
for () {
}
For the second code block, since there is no specific task mentioned, we can assume that we are just iterating over the list to perform some operation on each element. In this case, an enhanced for loop is more suitable because it is more concise and easier to read.
ArrayList<Integer> numbers = new ArrayList<>();
for (int number : numbers) {
int square = number * number;
System.out.println("The square of " + number + " is: " + square);
}
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.
double
valuesprivate 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;
}
int
valuesprivate int findMin(int [] values) {
int min = Integer.MAX_VALUE;
for (int currentValue: values) {
if (currentValue < min) {
min = currentValue;
}
}
return min;
}
Popcorn hack #1
// What needs to be changed to find the index of the max value? (write correct code in cell below)
private int findMax(double [] values) {
double max = values[0];
for (int index = 1; index < values.length; index++) {
max = values[index];
}
return max;
}
private int findMaxIndex(double[] values) {
if (values == null || values.length == 0) {
throw new IllegalArgumentException("Array is empty or null");
}
double max = values[0];
int maxIndex = 0;
for (int index = 1; index < values.length; index++) {
if (values[index] > max) {
max = values[index];
maxIndex = index;
}
}
return maxIndex;
}
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.
for
loopprivate 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;
}
enhanced
loopprivate 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? No, the order of accumulation does not matter in this case because we are summing up the values. Addition is commutative, which means that the order in which numbers are added does not affect the sum. Can you declare the variable inside the loop? In this specific case, you cannot declare the average variable inside the loop because it is used to accumulate the sum of getQuestionCount() values of all DebugDuck objects in the array. If you declare it inside the loop, it will be reinitialized to 0.0 in each iteration, and you will lose the accumulated sum. However, you can declare other variables inside the loop if needed.
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.
What kind of for loop should we use? Why? In this specific case, a regular for loop is used because we need to access the index of the array to perform the shift operation. An enhanced for loop would not be suitable because it does not provide access to the index of the array, only the values.
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.println(num + " ");
}
3
4
5
1
2
Why are we using the % operator? The % operator is used to handle the cases where the shift value is greater than the length of the array. It ensures that the index wraps around to the beginning of the array when it exceeds the length, creating a circular shift.
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[] words = {"alpha", "beta", "gamma", "delta"};
int shiftWord = 2;
String[] shiftedWords = new String[words.length];
for (int index = 0; index < words.length; index++) {
shiftedWords[Math.floorMod((index - shiftWord), words.length)] = words[index];
}
words = shiftedWords;
for (String word : words) {
System.out.println(word + " ");
}
Why should the array index be wrapped in a call to Math.abs? In the case of a right shift, wrapping the index in a call to Math.abs is not necessary because the index will always be positive. However, in the case of a left shift, the index could become negative after subtracting the shift value. Wrapping the index in Math.abs ensures that the index is always positive, preventing an ArrayIndexOutOfBoundsException.
Scoring Guidelines:
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.
public class CancerResearch {
public static void main(String[] args) {
String[] cancerTypes = {"Breast Cancer", "Lung Cancer", "Prostate Cancer", "Colon Cancer", "Melanoma"};
double[] survivalRates = {90.3, 18.6, 98.2, 64.5, 92.7};
System.out.println("Cancer Type\t\t5-Year Survival Rate (%)");
for (int i = 0; i < cancerTypes.length; i++) {
System.out.println(cancerTypes[i] + "\t\t" + survivalRates[i]);
}
}
}
CancerResearch.main(null)
Cancer Type 5-Year Survival Rate (%)
Breast Cancer 90.3
Lung Cancer 18.6
Prostate Cancer 98.2
Colon Cancer 64.5
Melanoma 92.7
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
public class PrimeNumbers {
public static void main(String[] args) {
int[] numbers = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
// Using a for loop
System.out.println("Prime numbers (for loop):");
for (int i = 0; i < numbers.length; i++) {
if (isPrime(numbers[i])) {
System.out.print(numbers[i] + " ");
}
}
System.out.println();
// Using a while loop
System.out.println("Prime numbers (while loop):");
int index = 0;
while (index < numbers.length) {
if (isPrime(numbers[index])) {
System.out.print(numbers[index] + " ");
}
index++;
}
System.out.println();
}
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
PrimeNumbers.main(null)
Prime numbers (for loop):
2 3 5 7 11 13
Prime numbers (while loop):
2 3 5 7 11 13
Multiple Choice Questions
Do NOT Run the code cells. Try to do this on your own.
String [] list = {"red", "yellow", "blue"};
for (int i = 0; i < list.length; i++)
{
System.out.print(list[i].length()+ "-" )
}
3-6-4-
So option C because “3-6-4-“ will be displayed because the program prints the length of each string in the list followed by a dash.
Write why you chose that answer! ________
int [] numbers = {3, -4, 6, -7, 2};
for(/*missing code*/)
{
System.out.println(numbers[i]);
}
Answer: B. “int i = 1; i < numbers.length; i++”
This code will iterate through the array starting from index 1 to the last index, printing all elements except the first one.
Write why you chose that answer! ________
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;
}
}
Answer: B. Change loop condition to: “i < arr.length/2”
This is because we only need to swap the first half of the array with the second half to reverse it. If we continue swapping for the entire length of the array, we will end up with the original array.
In case you are having trouble with question 3 the answer is B. Write about why!
public class ArrayLesson {
public static void main(String[] args) {
// 6.1 Array creation and access
String[] colors = {"red", "green", "blue"};
System.out.println(colors[1]);
// 6.2 Traversing Array
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
System.out.println("Sum: " + sum);
// 6.3 Enhanced for loop for arrays
for (int number : numbers) {
System.out.print(number + " ");
}
System.out.println();
// 6.4 Developing Algorithms Using arrays
int max = numbers[0];
for (int number : numbers) {
if (number > max) {
max = number;
}
}
System.out.println("Max: " + max);
}
}
ArrayLesson.main(null)
green
Sum: 15
1 2 3 4 5
Max: 5
public class StudentGrades {
public static void main(String[] args) {
// 6.1 Array creation and access
double[] grades = {85.5, 90.0, 78.0, 92.5, 88.0};
System.out.println("First grade: " + grades[0]);
// 6.2 Traversing Array
double sum = 0;
for (int i = 0; i < grades.length; i++) {
sum += grades[i];
}
System.out.println("Total: " + sum);
// 6.3 Enhanced for loop for arrays
for (double grade : grades) {
System.out.print(grade + " ");
}
System.out.println();
// 6.4 Developing Algorithms Using arrays
double maxGrade = grades[0];
for (double grade : grades) {
if (grade > maxGrade) {
maxGrade = grade;
}
}
System.out.println("Highest grade: " + maxGrade);
}
}
StudentGrades.main(null)
First grade: 85.5
Total: 434.0
85.5 90.0 78.0 92.5 88.0
Highest grade: 92.5