Skip to the content.

CSA Unit 6 - Hacks

Hacks for unit 6 team teach

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

System.out.println(Arrays.toString(numbers))
11
21
31
41
51
[10, 20, 30, 40, 50]

Popcorn Hack 1:

String[] languages = {"Java", "Python", "Markdown", "C++", "Go", "JavaScript", "HTML"};

for (String language : languages) {
    System.out.println(language);
};
Java
Python
Markdown
C++
Go
JavaScript
HTML

Notes:

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];

        
        for (int i = 1; i < array.length; i++) {
            
            if (array[i] > max) {
                max = array[i];  
            }
            if (array[i] < min) {
                min = array[i];  
            }
        }
        // The loop starts from the second element of the array (i = 1) and compares it with the first element (i = 0).

        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, 10, 12};

        
        findMaxAndMin(array);
    }
}
MaxMinInArray.main(null)
Maximum value: 12
Minimum value: -1

Popcorn Hack 2:

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];

        
        for (int i = 1; i < array.length; i++) {
            if (array[i] > max) {
                max = array[i];
            }
            if (array[i] < min) {
                min = array[i];  
            }
            if (array[i] > array[i-1]){
                System.out.println("Greater");
            }
            else if (array[i] < array[i-1]){
                System.out.println("Less");
            }
            else{
                System.out.println("Equal");
            }
        }

        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);
    }
}
MaxMinInArray.main(null)
Greater
Greater
Less
Greater
Less
Greater
Less
Greater
Maximum value: 12
Minimum value: -1
public class WordShifter {  
    public static void main(String[] args) {
        String[] words = {"alpha", "beta", "gamma", "delta"};
        int shiftWord = 1;
        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;
        }
        for (String word : words) {
            System.out.print(word + " ");
        }
    }
}
WordShifter.main(null)
beta gamma delta alpha 
public class WordShifter {  
    public static void main(String[] args) {
        String[] words = {"alpha", "beta", "gamma", "delta"};
        int shiftWord = 1;
        for (int count = 0; count < shiftWord; count++) {
            String temp = words[words.length - 1];
            for (int index = words.length - 1; index > 0; index--) {
                words[index] = words[index - 1];
            }
            words[0] = temp;
        }
        for (String word : words) {
            System.out.print(word + " ");
        }
    }
}
WordShifter.main(null);
delta alpha beta gamma 

Question: How would you find the index of the last element of the array, if you didn’t know how many elements there were in the array?

Answer: You use the length property and subtract 1 from it. so array[array.length - 1] would give you the last element of the array.

int [] array1 = new int[5];
System.out.println(Arrays.toString(array1));
[0, 0, 0, 0, 0]
int [] array2 = new int[] {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(array2));
[1, 2, 3, 4, 5]
int [] array = new int[] {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(array));

array[array.length - 1] = 6;
System.out.println(Arrays.toString(array));
[1, 2, 3, 4, 5]


[1, 2, 3, 4, 6]
import java.util.Arrays;

String[] city_array = new String[] {"San Diego", "Los Angeles", "San Francisco", "Sacramento"};

city_array[1] = "Sacramento";
System.out.println(Arrays.toString(city_array));
[San Diego, Sacramento, San Francisco, Sacramento]
import java.util.Arrays;

String[] city_array = new String[] {"San Diego", "Los Angeles", "San Francisco", "Sacramento"};
System.out.println(Arrays.toString(city_array));
[San Diego, Los Angeles, San Francisco, Sacramento]
String[] city_array = new String[] {"San Diego", "Los Angeles", "San Francisco", "Sacramento"};
System.out.println(city_array[0]);
San Diego
String[] city_array = new String[] {"San Diego", "Los Angeles", "San Francisco", "Sacramento"};
System.out.println(city_array[2]);
San Francisco
String[] city_array = new String[] {"San Diego", "Los Angeles", "San Francisco", "Sacramento"};
city_array[3] = "San Jose";

System.out.println(Arrays.toString(city_array));
[San Diego, Los Angeles, San Francisco, San Jose]
String[] city_array = new String[] {"San Diego", "Los Angeles", "San Francisco", "Sacramento"};

System.out.println(Arrays.toString(city_array));
[San Diego, Los Angeles, San Francisco, Sacramento]
public class oddIndexOnly {
    public static void main(String[] args) {
        int[] listOfNumbers = new int[] {1, 2, 3, 4, 5};
        for (int index=0; index<listOfNumbers.length; index+=2) {
            System.out.println(listOfNumbers[index]);
        }
    }
}
oddIndexOnly.main(null);
1
3
5
public class evenIndexOnly {
    public static void main(String[] args) {
        int[] listOfNumbers = new int[] {1, 2, 3, 4, 5};
        for (int index=1; index<listOfNumbers.length; index+=2) {
            System.out.println(listOfNumbers[index]);
        }
    }
}
evenIndexOnly.main(null);
2
4
public static int sumOfEvenNumbers(int[] arr) {
    int sum = 0;
    for (int index = 0; index < arr.length; index++) {
        if (arr[index] % 2 == 0) {
            sum += arr[index];
        }
    }
    return sum;
}

int[] arr = {1, 2, 3, 4, 5};
System.out.println(sumOfEvenNumbers(arr)); // Output: 6
6
int[] array = {1, 2, 3, 4, 5, 6, 7};
int index = 0;

for (int num : array) {
    if (index % 2 != 0) {  // Check if index is odd
        System.out.println(num);
    }
    index++;
}
2
4
6
public static int countOccurrences(int[] arr, int target) {
    int count = 0;
    for (int num : arr) {
        if (num == 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
public static void main(String[] args) {    
    int[] arr = new int[5];
    int position = 0;
    while (position < arr.length) {
        arr[position] = (int) (Math.random() * 100);
        position ++;
    }
    System.out.println(Arrays.toString(arr));
}
main(null);
[90, 95, 80, 80, 62]
// Write a method that traverses an array of integers and returns the index of the first negative number. If there are no negative numbers, return -1. Use a while loop.
public static int firstNegativeIndex(int[] arr) {
    int index = 0;
    while (index < arr.length) {
        if (arr[index] < 0) {
            return index;
        }
        index++;
    }
    return -1;
}

// Example usage:
int[] arr = {4, 7, -2, 5};// indexes are 0, 1, 2, 3 with correspondant as 4, 7, -2, 5
System.out.println(firstNegativeIndex(arr)); // Output: 2
2
int[] list = new int[5];
for (int index =0; index <= list.length; index++) {
    list[index] = (int) (Math.random() * 10);
}

// output
// ---------------------------------------------------------------------------
// java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
// 	at .(#141:1)
String[] list = {"red", "yellow", "blue"};
for (int i = 0; i < list.length; i++) {
    System.out.print(list[i].length() + "_");
}
// What is displayed after the code is executed?

// A. red_yellow_blue

// B. 3_3_3_

// C. 3_6_4_

// D. 3_3_

// E. 3_6_

// Answer: (C)

Consider the following code segment which is intended to display every other element in numbers, beginning with the first element: int[] numbers = {13, 33, 3, -3, -333}; for (/missing/) { System.out.print(numbers[i]); } Which of the following could replace /missing code/ to make the code work as intended?

(A) int i = 0; i < numbers. length 12; it+

(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

Answer (E)

Consider the method which is intended to reverse the order of the elements in arr. 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; } } Which of the following would fix the method so it works as intended?

(A) Change the loop condition to:

i < arr. length - 1 (B) Change the loop condition to:

i < arr.length/2 (C) Change the loop condition to:

i < arr.length/2 - 1 (D) Change lines 6 and 7 to:

arr[1] = arr[arr.length-1];

arr [arr.length-i] = temp; (E) Change the loop body to:

arr[1] = arr[arr.length-1-1];

arr [arr.length-1-1] = arr[i];

Answer: (B)

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

public static int findSecondLargest(int[] arr) {
    // find the second largest inside the array
    


// Example usage:
public static void main(String[] args) {
    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
}
int[] list = new int[5];
for (int index =0; index <= list.length; index++) {
    list[index] = (int) (Math.random() * 10);
}

// output
// ---------------------------------------------------------------------------
// java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
// 	at .(#141:1)

Popcorn Hack: Create four new INITIALIZED arrays, with int, string, double, and boolean types respectively. Print out the second element of each array to see the default values.

int[] intArray = new int[5];
System.out.println(intArray[1]);

String[] stringArray = new String[5];
System.out.println(stringArray[1]);

double[] doubleArray = new double[5];
System.out.println(doubleArray[1]);

boolean[] booleanArray = new boolean[5];
System.out.println(booleanArray[1]);
0
null
0.0
false

Unit 6.1 HW Hack

Practice MCQs Question 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) B. arr.indexOf(find) C. arr[arr.length].indexOf(find) D. arr[arr.length - 3].indexOf(find) E. arr[arr.length - 2].indexOf(find)

Answer (D) Because to find the third last element, you need to subtract 3 from the length of the array.

Question 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?

A. 2 B. 12 C. 15 D. 9 E. 8

Answer (C) because the method returns the sum of the second element of the array and half of the fifth element of the array. So, 9 + 6/2 = 12 or index 1 which is 9 + index 4 which is 6 and then divided by 2 all added up which is 15.

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

Unit 6.2 HW Hack

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.

public static int findSecondLargest(int[] arr) {
    /*
     * This function takes an array of integers as input and returns the second largest unique element in the array. 
     * If the array has less than 2 elements, the function should return -1.
     */
}

// Example usage:
public static void main(String[] args) {
    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
}
public static int findSecondLargest(int[] arr) {
    // Check if the array has less than 2 elements
    if (arr.length < 2) {
        return -1;
    }

    // Initialize variables to hold the largest and second largest elements
    int largest = Integer.MIN_VALUE;
    int secondLargest = Integer.MIN_VALUE;

    // First pass to find the largest element
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] > largest) {
            largest = arr[i];
        }
    }

    // Second pass to find the second largest element
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] > secondLargest && arr[i] < largest) {
            secondLargest = arr[i];
        }
    }

    // If secondLargest is still Integer.MIN_VALUE, it means there was no second largest element
    if (secondLargest == Integer.MIN_VALUE) {
        return -1;
    }

    return secondLargest;
}

// Example usage:
int[] arr = {3, 5, 7, 5, 6};
int[] arr1 = {5};

Boolean singleArr = false;

if (singleArr) {
    System.out.println(findSecondLargest(arr1)); // Output: -1
} 
else {
System.out.println(findSecondLargest(arr)); // Output: 6
}
6

Unit 6.3 HW 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));
Integer[] grades = {88, 93, 55, 68, 77};

// Print the grades
System.out.println("Grades: " + Arrays.toString(grades));

// Calculate the average using an enhanced for loop
int sum = 0;
for (int g : grades) {
    sum += g;
}
double average = (double) sum / grades.length;

System.out.println("Average grade: " + average);
Grades: [88, 93, 55, 68, 77]


Average grade: 76.2

Unit 6.4 HW Hack:

HW Hack: Go through the array in reverse order and output each object

Integer[] myArray = {0, 1, 2, 3, 4, 5};

for (int i=1; count < myArray.length; i++) {
    //Add code here
};
Integer[] myArray = {0, 1, 2, 3, 4, 5};

for (int i = 1; i <= myArray.length; i++) {
    System.out.print(myArray[myArray.length - i]);
}
543210

HW Hack: Print words while skipping every other word ("Alpha", "Gamma", "Beta", "Delta")

public class WordShifter {  
    public static void main(String[] args) {
        String[] words = {"alpha", "beta", "gamma", "delta"};
        int shiftWord = 2;
        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;
        }
        for (String word : words) {
            System.out.print(word + " ");
        }
    }
}
WordShifter.main(null)
public class WordShifter {  
    public static void main(String[] args) {
        String[] words = {"alpha", "beta", "gamma", "delta"};
        int shiftWord = 0;
        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;
        }
        int index = 0;
        for (String word : words) {
            if (index % 2 != 0) {
                System.out.print(word + " ");
            }
            index++;
        }
    }
}
WordShifter.main(null)
beta delta 
public class GradeSearch {
    public static String searchGrade(String[][] grades, String name) {
                // Loop through each row in the grades array
        for (String[] row : grades) {
            // Check if the first element (name) matches the search name
            if (row[0].equals(name)) {
                // Return the second element (grade) if the name matches
                return row[1];
            }
        }
        // Return a message if the student is not found
        return "Student not found";
    }

    public static void main(String[] args) {
        // Sample 2D array with names and grades
        String[][] grades = {
            {"John", "93"},
            {"Alice", "85"},
            {"Bob", "78"},
            {"Eve", "92"}
        };

        // Test the search function
        String nameToSearch = "Alice";
        String grade = searchGrade(grades, nameToSearch);
        System.out.println(nameToSearch + "'s grade: " + grade);

        nameToSearch = "Charlie";
        grade = searchGrade(grades, nameToSearch);
        System.out.println(nameToSearch + "'s grade: " + grade);
    }
}

// Execute the main method to see the output
GradeSearch.main(null);
Alice's grade: 85
Charlie's grade: Student not found