1
a.
Answer:
public static int arraySum(int[] arr) {
// Initialize a variable to hold the sum
int sum = 0;
// Iterate over each element in the array
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
int[] arr = {1, 3, 2, 7, 3};
int sum = arraySum(arr);
System.out.println("The sum of the array is: " + sum);
code output:
The sum of the array is: 16
b.
Answer:
Answer:
public static int[] rowSums(int[][] arr2D) {
int numRows = arr2D.length; // Get the number of rows in the 2D array
int[] sums = new int[numRows]; // Create a new 1D array to store the row sumsw
for (int i = 0; i < numRows; i++) {
sums[i] = arraySum(arr2D[i]); // Use the arraySum method to calculate the sum of each row and store it in the sums array
}
return sums;
}
//2d array 1-9 but i cant commit if it is here, so just imagine it divided into three brackets
int[] sums = rowSums(arr2D);
for (int i = 0; i < sums.length; i++) {
System.out.println("The sum of row " + i + " is: " + sums[i]);
}
The sum of row 0 is: 6
The sum of row 1 is: 15
The sum of row 2 is: 24
c.
Answer:
FRQ #1
public class ArraySum { //class
// This method takes an array of integers as input and returns their sum
public static int arraySum(int[] arr) {
// Initialize a variable to hold the sum
int sum = 0;
// Iterate over each element in the array
for (int i = 0; i < arr.length; i++) {
// Add the current element to the sum
sum += arr[i];
}
// Return the total sum
return sum;
}
public static void main(String[] args) { //main method
// Define an array of integers
int[] arr = {1, 3, 2, 7, 3};
// Calculate the sum of the array elements
int sum = arraySum(arr); // 16
System.out.println("The sum of the array is: " + sum); //prints out "the sum of the array"
}
}
ArraySum.main(null);
The sum of the array is: 16