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

Situation: You are developing a game where you need to track player scores on a 2D grid representing levels and attempts.

(a) Explain the concept of iteration over a 2D array in Java. Provide an example scenario where iterating over a 2D array is useful in a programming task.

When iterating over a 2D array in Java, you traverse through each element of the array using nested loops. One loop will iterate over the rows and the other loop will iterate over the columns of the array. An example scenario where iterating over a 2D array is useful in a programming task is when going through matrix operations (mathematics). When operating over a matrix, you have to go through each element and perform different mathematical operations.

(b) Code:

You need to implement a method calculateTotalScore that takes a 2D array scores of integers representing player scores and returns the sum of all the elements in the array. Write the method signature and the method implementation. Include comments to explain your code.

public class ScoreCalculator {
    
    // Method to calculate the total score of all players
    public static int calculateTotalScore(int[][] scores) {
        int totalScore = 0; // Initialize total score
        
        // Iterate over each row (player)
        for (int i = 0; i < scores.length; i++) {
            // Iterate over each column (score of a player)
            for (int j = 0; j < scores[i].length; j++) {
                totalScore += scores[i][j]; // Add the score to the total
            }
        }
        
        return totalScore; // Return the total score
    }

    public static void main(String[] args) {
        // array of scores
        int[][] scores = {
            {10, 20, 30},
            {15, 25, 35},
            {12, 22, 32}
        };
        
        // total score
        int totalScore = calculateTotalScore(scores);
        
        // print score
        System.out.println("Total Score: " + totalScore);
    }
}

ScoreCalculator.main(null);
Total Score: 201

Question 4: Math Class (Unit 2)

(a) Discuss the purpose and utility of the Math class in Java programming. Provide examples of at least three methods provided by the Math class and explain their usage.

The Math class in Java provides a set of methods for performing math operations. It is a class that has many static methods and constants for common mathematical functions and constants.

(b) You need to implement a method calculateSquareRoot that takes a double number as input and returns its square root using the Math class. Write the method signature and the method implementation. Include comments to explain your code.

public class SquareRootCalculator {
    
    // method
    public static double calculateSquareRoot(double number) {
        double squareRoot = Math.sqrt(number); // use math.sort
        return squareRoot; // return square root
    }

    public static void main(String[] args) {
        double number = 25.0; // using 25
        double squareRoot = calculateSquareRoot(number); // calc square root
        System.out.println("Square root of " + number + " is " + squareRoot); // print
    }
}

SquareRootCalculator.main(null);
Square root of 25.0 is 5.0

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

(a) Explain the roles and usage of the if statement, while loop, and else statement in Java programming. Provide examples illustrating each.

If statements allow you to execute a block of code only if a specified condition is true.

if (condition) {
    // if condition is true -->, executes this code here
}

While loops are used to keep repeating a certain block of code until a condition is met. It is good for iterative tasks.

while (condition) {
    // until condition is true..
}

Else statements are used with if statements to ensure that there is a block of code carried out if the conditions of an if statement are not met.

if (condition) {
    // if condition is true..
} else {
    // if condition is false..
}

(b) You need to implement a method printGradeStatus that takes an integer score as input and prints “Pass” if the score is greater than or equal to 60, and “Fail” otherwise. Write the method signature and the method implementation. Include comments to explain your code.

public class GradeStatusPrinter {
    
    // Method to print the grade status based on the score
    public static void printGradeStatus(int score) {
        if (score >= 60) { // Check if the score is greater than or equal to 60
            System.out.println("Pass"); // pass condition
        } else {
            System.out.println("Fail"); // fail condition
        }
    }

    public static void main(String[] args) {
        // Test cases
        printGradeStatus(75); 
        printGradeStatus(45); 
        printGradeStatus(60); 
    }
}

GradeStatusPrinter.main(null);

Pass
Fail
Pass