Question:
Consider a program that tracks the sales of various products in different regions. The data is stored in a multidimensional array where the rows represent the regions and the columns represent the products. Each entry in the array represents the number of units sold for a specific product in a specific region.
Write a method named getTotalSales that takes in a multidimensional array and returns the total number of units sold across all regions and products.
The method signature is:
public static int getTotalSales(int[][] salesData)
For example, given the following salesData array:
int[][] salesData = {
{4, 7, 2},
{3, 5, 9},
{8, 1, 6}
};
The getTotalSales method should return 45 since the total number of units sold is 45.
Provide your implementation of the getTotalSales method, and explain your approach in detail.
Answer:
public class MultidimensionalArrayExample {
public static void main(String[] args) {
int[][] salesData = {
{4, 7, 2},
{3, 5, 9},
{8, 1, 6}
};
int totalSales = getTotalSales(salesData);
System.out.println("Total sales: " + totalSales);
}
public static int getTotalSales(int[][] salesData) {
int total = 0;
// Iterate through each row (region)
for (int row = 0; row < salesData.length; row++) {
// Iterate through each column (product)
for (int col = 0; col < salesData[row].length; col++) {
// Add the value in the current cell to the total
total += salesData[row][col];
}
}
return total;
}
}
Explanation:
getTotalSales method takes in a multidimensional array salesData as a parameter and returns the total number of units sold across all regions and products.total to keep track of the cumulative sales.for loops to iterate through each cell in the salesData array.
row.col.total variable.total value, which represents the total number of units sold.In the given example, the salesData array is:
int[][] salesData = {
{4, 7, 2},
{3, 5, 9},
{8, 1, 6}
};
The nested for loops iterate through each cell of the array:
row is 0 and col is 0, so the value 4 is added to the total.row is 0 and col is 1, so the value 7 is added to the total.row is 0 and col is 2, so the value 2 is added to the total.total value becomes 45, representing the total number of units sold.