44.0k views
3 votes
What is the value of the average variable after the following code is executed? var sum = 0; var prices = [14, 10, 9, 12, 11, 14, 10, 8]; for( var i = 0; i < prices.length; i++ ) { sum = sum + prices[i]; } var average = sum/prices.length;

1 Answer

7 votes

Answer:

The value of average is 11

Step-by-step explanation:

Analyzing the program line by line

This line initializes sum to 0

var sum = 0;

This line defines an array named prices and it also fills it with integer values.

var prices = [14, 10, 9, 12, 11, 14, 10, 8];

The italicized lines is an iteration that adds every element of prices and saves the result in variable sum

for( var i = 0; i < prices.length; i++ ) {

sum = sum + prices[i];

}

At this point, the value of sum is 88

The next line divides the value of sum (88) by the length of the array (8) which gives 11.

11 is then saved in variable average

var average = sum/prices.length;

User TheQman
by
3.9k points