Lesson for APCSA Unit 6. Authors are Sreeja, Tanisha, Vivian, and Isabelle
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
int[] arr = {7, 2, 5, 3, 0, 10};
for (int k = 0; k < arr.length - 1; k++) {
if (arr[k] > arr[k+1]) {
System.out.print(k + " " + arr[k] + " ");
}
}
0 7 2 5 3 3
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
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
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
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!
change the index to increase by 2
change the index inital value to 1, change to index += 2 in for loop
// 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.
since we go to each value, the loop accomplishes traversing the array.
int [] list = new int[5];
int index = 0;
while (index < list.length)
{
// Do something
index ++;
}
the i variable was defined inside loop, so it won’t be used outside of the loop.
When traversing an array, we need to be careful with the indices to avoid an ArrayIndexOutOfBoundsException being thrown.
ATTENTION: MOST COMMON MISTAKE:
the loops are going out of bounds of our set arrays, the for loop is going 1 back the set limit of for loops. while loop is going 1 back the set limit of while loops.
for(int i = 0; i <= list.length; i ++)
Incomplete input:
| for(int i = 0; i <= list.length; i ++)
int index = 0;
while (index <= list.length)
Incomplete input:
| 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 ++)
Incomplete input:
| // 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; /* missing code */
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;
}
int i = 0;
public void printQuotesWithEmotions() {
// Make a change in the code here!
for (String emotion : emotions) {
String quote = quotes.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: "Success is not final, failure is not fatal: It is the courage to continue that counts."
Emotion: Passionate
---------------------------
Quote: "Success is not final, failure is not fatal: It is the courage to continue that counts."
Emotion: Innovative
---------------------------
What are some of the benefits of using an enhanced for loop in this case versus a regular for loop?
a regular for loop allows you to access indices but an enchanced for loop cannot. Enchanced for loops are useful when you want to iterate through an array but not access the index.
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 (String name : names) {
if (name.equals(searchName)) {
System.out.println("Found " + searchName);
break;
}
}
ArrayList<Integer> numbers = new ArrayList<>();
// use normal for loop
//code goes here
for (int i = 0; i < numbers.size(); i++) {
System.out.println(numbers.get(i));
}
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];
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, because we accumulate all of the values at the end, regardless of change in order. we only need sum, not specific value, and changing order doesn’t change sum.
Can you declare the variable inside the loop?
no, then we won’t be able to access the variable outside the loop.
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?
use a normal for loop because we need to access specific indices.
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?
we use this to prevent our index going out of bounds, and it creates the shift
Popcorn hack #2
How would we code a left shift? Write a left shift using the variables below
String[] words = {"w", "x", "y", "z"};
String[] wordShift = new String[words.length];
int shiftWord = 2;
for (int index = 0; index < words.length; index++) {
wordShift[index] = words[((index + shiftWord) % words.length)];
System.out.println(wordShift[index]);
}
y
z
w
x
Why should the array index be wrapped in a call to Math.abs?
Math.abs returns absolute value, so we probably use this to make sure our array index doesn’t go out of bounds.
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.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class MyObject {
int id;
public MyObject(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
public class ObjectSorter {
public static void main(String[] args) {
List<MyObject> objects = new ArrayList<>();
// Add some objects with IDs
objects.add(new MyObject(3));
objects.add(new MyObject(1));
objects.add(new MyObject(2));
// Sort the objects based on their IDs
Collections.sort(objects, (o1, o2) -> Integer.compare(o1.getId(), o2.getId()));
// Print the sorted objects
for (MyObject obj : objects) {
System.out.println("Object ID: " + obj.getId());
}
}
}
ObjectSorter.main(null);
Object ID: 1
Object ID: 2
Object ID: 3
// Experiment with hashmaps to accomplish similar task
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class MyObject {
int id;
public MyObject(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
public class ObjectSorterWithHashMap {
public static void main(String[] args) {
List<MyObject> objects = new ArrayList<>();
Map<Integer, MyObject> objectMap = new HashMap<>();
// Add some objects with IDs
MyObject obj1 = new MyObject(3);
MyObject obj2 = new MyObject(1);
MyObject obj3 = new MyObject(2);
objects.add(obj1);
objects.add(obj2);
objects.add(obj3);
// Populate the HashMap with objects
for (MyObject obj : objects) {
objectMap.put(obj.getId(), obj);
}
// Sort the objects by ID
List<MyObject> sortedObjects = new ArrayList<>(objectMap.values());
Collections.sort(sortedObjects, Comparator.comparing(MyObject::getId));
// Print the sorted objects
for (MyObject obj : sortedObjects) {
System.out.println("Object ID: " + obj.getId());
}
}
}
ObjectSorterWithHashMap.main(null);
Object ID: 1
Object ID: 2
Object ID: 3
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 PrimeNumberFinder {
public static void main(String[] args) {
int[] numbers = {2, 7, 15, 17, 23, 30, 37, 45};
System.out.println("Prime numbers using a for loop:");
for (int num : numbers) {
if (isPrime(num)) {
System.out.print(num + " ");
}
}
System.out.println(); // Newline
System.out.println("Prime numbers using a while loop:");
int i = 0;
while (i < numbers.length) {
if (isPrime(numbers[i])) {
System.out.print(numbers[i] + " ");
}
i++;
}
}
// Check if a number is prime
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
if (num <= 3) {
return true;
}
if (num % 2 == 0 || num % 3 == 0) {
return false;
}
for (int i = 5; i * i <= num; i += 6) {
if (num % i == 0 || num % (i + 2) == 0) {
return false;
}
}
return true;
}
}
PrimeNumberFinder.main(null);
Prime numbers using a for loop:
2 7 17 23 37
Prime numbers using a while loop:
2 7 17 23 37
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()+ "-" );
}
Write why you chose that answer!
B because the print statement just prints out the length of the list, and the statement runs 3 times, also the array never changes. ________
int [] numbers = {3, -4, 6, -7, 2};
for(/*missing code*/)
{
System.out.println(numbers[i]);
}
Write why you chose that answer!
E, because then we print out the 1st, 3rd, and 5th elements of the array, skipping 2nd and 4th since we go by 2 in the loop. ________
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;
}
}
In case you are having trouble with question 3 the answer is B. Write about why!
the Answer is B but I think its because dividing the array length my 2 would let us start somewhere else where the code would thus reverse the items for our goal.