Unit 6 - Arrays
Unit 6.1
Popcorn Hack 1
String[] city_array = {"San Diego", "Los Angeles", "San Francisco", "Sacramento"};
System.out.println(city_array[0]);
System.out.println(city_array[2]);
System.out.println(city_array[3]);
city_array[1] = "Sacaramento";
city_array[3] = "San Jose";
System.out.println(city_array.length);
San Diego
San Francisco
Sacramento
4
Popcorn Hack 2
// Creating initialized arrays with default values
int[] intArray = new int[4]; // defaults to 0
String[] stringArray = new String[4]; // defaults to null
double[] doubleArray = new double[4]; // defaults to 0.0
boolean[] booleanArray = new boolean[4]; // defaults to false
// Printing the second element (index 1) of each array
System.out.println("Second element of intArray: " + intArray[1]);
System.out.println("Second element of stringArray: " + stringArray[1]);
System.out.println("Second element of doubleArray: " + doubleArray[1]);
System.out.println("Second element of booleanArray: " + booleanArray[1]);
Second element of intArray: 0
Second element of stringArray: null
Second element of doubleArray: 0.0
Second element of booleanArray: false
MCQ
1
Consider the following method which is intended to return the position of find
within the String referenced at the third last index of arr
.
public static int findThirdLast(String [] arr, String find) {
return /*missing code*/;
}
Which of the following could replace /*missing code*/
to complete the method as specified?
A. arr[].indexOf(find)
arr[] doesn’t correctly reference any specified element
B. arr.indexOf(find)
arr is an array which doesn’t support indexOf
C. arr[arr.length].indexOf(find)
this would cause an out of bounds exception
D. arr[arr.length - 3].indexOf(find)
correct. It will get the third last element array
E. arr[arr.length - 2].indexOf(find)
this will get the second last element
public static int findThirdLast(String [] arrtest, String find)
{
return arrtest[arrtest.length-3].indexOf(find);
}
String [] testArray = {"cat", "dog", "horse", "monkey", "snake", "elephant"};
int result = findThirdLast(testArray, "on");
System.out.println(result);
1
2
Consider the following method:
public static int mystery(int [] arr) {
return arr[1] + arr[4]/2
}
The mystery
method is called from another method in the same class: int[] list = {1,9,2,5,6}; int result = mystery(list);
What is stored in result after executing the above code?
The code takes in an array of integers. It accesses the second element (index 1). It accesses the fifth element (index 1) and divides that by 2: 6 / 2 = 3. It adds that to the second element: 9 + 3 = 12.
A. 2 B. 12 (correct) C. 15 D. 9 E. 8
public static int mystery(int [] myarr)
{
return myarr[1] + myarr[4]/2;
}
int[] list = {1,9,2,5,6};
int result = mystery(list);
System.out.println(result);
12
Unit 6.2
Popcorn Hack 1
public static int sumOfEvenNumbers(int[] arr) {
int total = 0;
for (int i = 0; i < 5; i++) {
if (arr[i] % 2 == 0) {
total += arr[i];
}
}
return total;
}
// Example usage:
int[] arr = {1, 2, 3, 4, 5};
System.out.println(sumOfEvenNumbers(arr)); // Output: 6
6
Popcorn Hack 2
public static int countOccurrences(int[] arr, int target) {
int count = 0;
for (int current: arr) {
if (current == target) {
count++;
}
}
return count;
}
// Example usage:
int[] arr = {3, 5, 3, 3, 7, 5};
int target = 3;
System.out.println(countOccurrences(arr, target)); // Output: 3
3
Popcorn Hack 3
public static int firstNegativeIndex(int[] arr) {
int return_ = 0;
for (int current : arr) {
if (current < 0) {
return_ = current;
}
}
return return_;
}
// Example usage:
int[] arr = {4, 7, -2, 5};
System.out.println(firstNegativeIndex(arr)); // Output: -2
-2
MCQ
1
String[] list = {"red", "yellow", "blue"};
for (int i = 0; i < list.length; i++) {
System.out.print(list[i].length() + "_");
}
3_6_4_
C: 36_4 will be displayed. It finds the length of each word and appends an “_” to it. It prints that.
int[] numbers = {13, 33, 3, -3, -333};
for (int i = 0; i < numbers.length; i += 2) {
System.out.println(numbers[i]);
}
13
3
-333
E: int i = 0; i < numbers.length; i+=2. It skips every other number and prints.
1
public static void reverseArray (double [] arr) {
for (int i = 0; i < arr.length; i++) {
double temp = arr [i];
arr[i] = arr[arr.length-1-i];
arr[arr.length-1-i] = temp;
}
}
The method is supposed to reverse the array.
(A) Change the loop condition to:
i < arr. length - 1
: iterates the entire array until arr.length - 2
which doesn’t fix the issue
(B) Change the loop condition to:
i < arr.length/2
: correct solution since it iterates to the middle of the array and swaps the correct elements. If we have a 5 element array, it swaps 0 and 4, 1 and 3, 2 and 2. It stops. This reverses the array.
(C) Change the loop condition to:
i < arr.length/2 - 1
: stops loop too early
(D) Change lines 6 and 7 to:
arr[1] = arr[arr.length-1];
arr [arr.length-i] = temp;
Only manipulates arr[1]
.
(E) Change the loop body to:
arr[1] = arr[arr.length-1-1];
arr [arr.length-1-1] = arr[i];
Changes a specific element again instead of swapping all the elements.
Homework Hack
Problem Statement: Given an array of integers, write a method to find the second largest unique element in the array. If the array has fewer than two distinct elements, return -1.
import java.util.*;
public static int findSecondLargest(int[] arr) {
// Edge case: If the array has less than two elements, return -1
if (arr.length < 2) {
return -1;
}
// Use a TreeSet to store unique elements in sorted order
TreeSet<Integer> uniqueElements = new TreeSet<>();
for (int num : arr) {
uniqueElements.add(num);
}
// If there are fewer than two unique elements, return -1
if (uniqueElements.size() < 2) {
return -1;
}
// Remove the largest element
uniqueElements.pollLast();
// The new largest element is the second largest original element
return uniqueElements.last();
}
int[] arr1 = {3, 1, 4, 1, 5, 9, 2, 6};
System.out.println(findSecondLargest(arr1)); // Output: 6
int[] arr2 = {10, 10, 10, 10};
System.out.println(findSecondLargest(arr2)); // Output: -1
6
-1
Unit 6.3
Popcorn Hack 1
String[] array = {"Java", "Python", "Markdown", "C++", "Go", "JavaScript", "HTML"};
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
};
Java
Python
Markdown
C++
Go
JavaScript
HTML
Popcorn Hack 2
private String[] myArray = {
"And", "Table", "Shirts", "Tea", "School Day"
};
for (String currentWord : myArray) {
System.out.println(currentWord.length());
}
3
5
6
3
10
D: System.out.println(currentWord.length());
It prints out the currentWord’s length.
Popcorn hack 3
String[] fruits = {"Apple", "Banana", "Orange"};
for (String fruit : fruits) {
// Find the index of the letter 'a' in each fruit
int index = fruit.toLowerCase().indexOf('a'); // Using toLowerCase to make it case-insensitive
System.out.println("The index of 'a' in " + fruit + " is: " + index);
}
The index of 'a' in Apple is: 0
The index of 'a' in Banana is: 1
The index of 'a' in Orange is: 2
Popcorn Hack 4
String[] myArray = {"Object 1", "Object 2", "Object 3", "Object 4", "Object 5"};
for (currentWord: myArray) {
System.out(currentWord)
};
// There are 3 errors, can you find them?
- For loop needs a declaration:
for (String currentWord : myArray) {
. Notice howString
was added. - Print syntax needs to be fixed:
System.out.println(currentWord);
. It wasSystem.out(currentWord)
before. - Add a missing semicolon:
System.out.println(currentWord);
. It wasSystem.out(currentWord)
before.
String[] myArray = {"Object 1", "Object 2", "Object 3", "Object 4", "Object 5"};
for (String currentWord : myArray) {
System.out.println(currentWord);
}
Object 1
Object 2
Object 3
Object 4
Object 5
Final Hack
Add to the code below to create a average grade calculator (using an enhanced for loop)
Integer[] grades = {88, 93, 55, 68, 77};
Scanner userGrades = new Scanner(System.in);
System.out.print("Enter a grade: ");
int grade = Integer.parseInt(userGrades.nextLine());
// Add code here to take the average
grades = Arrays.copyOf(grades, grades.length + 1);
grades[grades.length - 1] = grade;
System.out.println(Arrays.toString(grades));
import java.util.Arrays;
import java.util.Scanner;
// Initial grades
Integer[] grades = {88, 93, 55, 68, 77};
// Take user input for a new grade
Scanner userGrades = new Scanner(System.in);
System.out.print("Enter a grade: ");
int grade = Integer.parseInt(userGrades.nextLine());
// Add the new grade to the array
grades = Arrays.copyOf(grades, grades.length + 1);
grades[grades.length - 1] = grade;
System.out.println("Updated grades: " + Arrays.toString(grades));
// Calculate the average using an enhanced for loop
int sum = 0;
for (int g : grades) {
sum += g;
}
double average = sum / (double) grades.length; // Cast to double for decimal precision
System.out.println("Average grade: " + average);
Enter a grade: Updated grades: [88, 93, 55, 68, 77, 100]
Average grade: 80.16666666666667
Unit 6.4
Popcorn Hack 1
public class MaxMinInArray {
public static void findMaxAndMin(int[] array) {
if (array == null || array.length == 0) {
System.out.println("Array is empty");
return;
}
int max = array[0];
int min = array[0];
// Loop through the array, starting from the first element
for (int i = 0; i < array.length - 1; i++) { // Iterate until the second-last element
// Check if the current element is greater than the next one
if (array[i] > array[i + 1]) {
System.out.println("Increase: " + array[i] + " > " + array[i + 1]);
}
}
// Loop to find max and min
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
if (array[i] < min) {
min = array[i];
}
}
System.out.println("Maximum value: " + max);
System.out.println("Minimum value: " + min);
}
public static void main(String[] args) {
int[] array = {3, 5, 7, 2, 8, -1, 4, 0, 12};
findMaxAndMin(array);
}
}
Homework Hack 1
Integer[] myArray = {0, 1, 2, 3, 4, 5};
// Loop through the array in reverse order
for (int i = myArray.length - 1; i >= 0; i--) {
System.out.println(myArray[i]);
}
5
4
3
2
1
0
Homework Hack 2
public class WordShifter {
public static void main(String[] args) {
String[] words = {"alpha", "beta", "gamma", "delta"};
int shiftWord = 2;
// Shift the words to the left by the specified number of positions
for (int count = 0; count < shiftWord; count++) {
String temp = words[0];
for (int index = 0; index < words.length - 1; index++) {
words[index] = words[index + 1];
}
words[words.length - 1] = temp;
}
// Print every other word
for (int i = 0; i < words.length; i += 2) {
System.out.print(words[i] + " ");
}
}
}