190k views
0 votes
For this exercise, use the following 2D array, which is already declared and initialized in your programming environment below. Do not rename the provided array - your program should refer to it as a. 34 38 50 44 39 42 36 40 43 44 24 31 46 40 45 43 47 35 31 26 37 28 20 36 50 Your task is to output the sum of all values in the 2D array, along with the average of all values in the 2D array, as seen in the sample run below. Note: Be sure that your program accounts for arrays of any size, not just arrays that are 5 x 5. Your program will be tested against arrays of size n by n. It should work for any square array, not just the one shown. You should also use for loops in your program, not while loops. Sample Run Sum of all values: 949 Average of all values: 37.96

User FluffyJack
by
7.9k points

1 Answer

6 votes

Final answer:

To find the sum and average of all values in a 2D array, initialize variables for sum and count to 0, iterate over each element with nested for loops, add elements to sum, increment count, and then divide sum by count for the average.

Step-by-step explanation:

To calculate the sum and the average of all values in a 2D array, first, we need to initialize two variables sum and count, which will hold the total sum of all the numbers in the array and the count of those numbers, respectively. We then use nested for loops to iterate over each element of the array, adding each element to sum and incrementing count by 1 for each element. After iterating over all elements in the array, we calculate the average by dividing the sum by the count. Finally, we output both the sum and the average to complete the task.

Here's a pseudocode example:

  • Initialize the variable sum to 0.
  • Initialize the variable count to 0.
  • Use a for loop to iterate over each row of the array.
  • Nest another for loop inside to iterate over each element of the row.
  • Add each element to sum and increment count.
  • After all iterations, divide sum by count to get the average.
  • Print out the sum and the average.

Here's a sample output based on the given values:

Sum of all values: 949

Average of all values: 37.96

User Alejandro Huerta
by
8.0k points