Question 2: Iteration over 2D arrays (Unit 4)

A.

  • To iterate over to 2D arrays it typically requires 2 nested loops that can iterate through the super array and the sub array
  • One example of the use of a 2D array is in a farming simulator, in this case the simulator uses a 2D tile-based system to place and remove crops. To do this the array must be iterated over.

B.

public static int calculateTotalScore(int[][] scores){
    int totalScore = 0;

    // Iterate through each row (student)
    for (int i = 0; i < scores.length; i++) {
        // Iterate through each column (score for a student)
        for(int j = 0; j < scores[i].length; j++){
            // Add the score to the total
            totalScore += scores[i][j];
        }
    }
    return totalScore;
}

// Example usage
int[][] scores = {
    {80, 90, 95},
    {70, 85, 88},
    {60, 75, 82}
};

int totalScore = calculateTotalScore(scores);
System.out.println("Total score: " + totalScore);
Total score: 725

Question 4: Math Class (Unit 2)

A.

The Math class in Java provides a set of static methods for performing common mathematical operations. It is part of the Java standard library and is widely used in various applications for performing calculations. Some of the key purposes and utilities of the Math class include:

Math.addExact((int) a, (int) b); // Adds two integers safely without overflow
Math.sin(angle); // Calculate sine value
Math.pow(base, exponent); // Calculate base raised to the power exponent

B.

/**
 * Calculates the square root of a double number using the Math class.
 *
 * @param number the input number whose square root is to be calculated
 * @return the square root of the input number
 */
public static double calculateSquareRoot(double number) {
    return Math.sqrt(number);
}


double number = 25.0;
double squareRoot = calculateSquareRoot(number);
System.out.println("Square root of " + number + " is: " + squareRoot);
Square root of 25.0 is: 5.0

Question 5: If, While, Else (Unit 3-4)

A.

If

  • It allows you to execute a block of code only if a specified condition is true.

While

  • used for repetitive execution of a block of code as long as a specified condition is true.

Else

  • The else statement is used in conjunction with the if statement to specify the block of code that should be executed if the if condition evaluates to false.

B.

public static void printGradeStatus(int score){
    if(score >= 60){
        System.out.println("Pass");
    }else{
        System.out.println("Fail");
    }
}

printGradeStatus(61);
printGradeStatus(59);
Pass
Fail