Question:
A company wants to keep track of the sales of their products in different regions. They have decided to use a multidimensional array to store this data. Each row of the array represents a region, and each column represents a quarter of the year. Each element in the array represents the number of units sold in a particular region and quarter.
You are given the following array that represents the sales data for the company:
int[][] salesData = {
{10, 20, 30, 40},
{15, 25, 35, 45},
{20, 30, 40, 50},
{25, 35, 45, 55}
};
Write a Java method getTotalSales()
that takes the sales data array as a parameter and returns the total number of units sold by the company.
Signature:
public static int getTotalSales(int[][] salesData)
Example:
If the given sales data array is:
int[][] salesData = {
{10, 20, 30, 40},
{15, 25, 35, 45},
{20, 30, 40, 50},
{25, 35, 45, 55}
};
Then the method getTotalSales(salesData)
should return 470
.
Explanation:
The given sales data array represents the following sales data:
Region | Q1 | Q2 | Q3 | Q4 |
---|---|---|---|---|
R1 | 10 | 20 | 30 | 40 |
R2 | 15 | 25 | 35 | 45 |
R3 | 20 | 30 | 40 | 50 |
R4 | 25 | 35 | 45 | 55 |
To calculate the total number of units sold, we need to sum up all the elements in the array. Performing the addition, we get 10 + 20 + 30 + 40 + 15 + 25 + 35 + 45 + 20 + 30 + 40 + 50 + 25 + 35 + 45 + 55 = 470
.
Therefore, the correct answer is 470
.
Java Solution:
public class Main {
public static void main(String[] args) {
int[][] salesData = {
{10, 20, 30, 40},
{15, 25, 35, 45},
{20, 30, 40, 50},
{25, 35, 45, 55}
};
int totalSales = getTotalSales(salesData);
System.out.println("Total sales: " + totalSales);
}
public static int getTotalSales(int[][] salesData) {
int total = 0;
for (int i = 0; i < salesData.length; i++) {
for (int j = 0; j < salesData[i].length; j++) {
total += salesData[i][j];
}
}
return total;
}
}
Output:
Total sales: 470
In the given solution, we iterate over each element in the salesData
array using nested for
loops. The outer loop iterates over the rows (regions) of the array, and the inner loop iterates over the columns (quarters) of the array.
Inside the loops, we add each element to the total
variable using the +=
operator. This accumulates the sum of all elements in the array.
Finally, we return the total
value, which represents the total number of units sold by the company.