69.9k views
4 votes
Please Help!

Assume that you have an array named items containing 100 integers, and an integer named numItems that represents the number of valid integers currently used in the array. All elements from items[numItems] to items[items.length-1] have values of 0.


The following code is designed to calculate and print the average of the valid array elements:

int sum=0, count;
for (count = 0; count < items. length; count++)
{
statement 1
}
statement 2


Which of the following substitutions for and will cause this code to correctly print the average of the valid array elements in items?


A. Statement 1:
sum += items[count];

Statement 2:
System.out.println((double)sum / count);

B. Statement 1:
sum += items[count];

Statement 2:
System.out.println((double)sum / items.length);

C. Statement 1:
sum += items[count];

Statement 2:
System.out.println((double)sum / numItems);

D. Statement 1:
sum += items[items.length-1];

Statement 2:
System.out.println(sum / 100);

E. Statement 1:
sum += items[items.length-1];

Statement 2:
System.out.println((double)sum / numItems);

User Alex Chan
by
4.6k points

1 Answer

2 votes

Answer:

The answer to this question is given below in the explanation section.

Step-by-step explanation:

This question is about calculating the sum and average of the elements in the given array.

The code is given below:

int sum=0, count;

for (count = 0; count < items. length; count++)

{

statement 1

}

statement 2

Then this question is asked that which of the following substitutions for and will cause this code to correctly print the average of the valid array elements in items?

So, The correct answer is A. Because the first statement counts the sum of all the given elements in the array. And, the second statement print the average (sum/count) and store result in double.

A. Statement 1:

sum += items[count];

Statement 2:

System.out.println((double)sum / count);

So that the correct and complete program is given below:

int sum=0, count;

for (count = 0; count < items. length; count++)

{

sum += items[count];

}

System.out.println((double)sum / count);

User Mit Mehta
by
6.1k points