85.5k views
3 votes
A programmer wrote the code segment below to display the average of all the elements in a list called numbers. There is always at least one number in the list.

Line 1: count ← 0
Line 2: sum ← 0
Line 3: FOR EACH value IN numbers
Line 4: {
Line 5: count ← count + 1
Line 6: sum ← sum + value
Line 7: average ← sum / count
Line 8: }
Line 9: DISPLAY (average)

The programmer wants to reduce the number of operations that are performed when the program is run. Which change will result in a correct program with a reduced number of operations performed?
Select one:
a. Interchanging line 1 and line 2
b. Interchanging line 5 and line 6
c. Interchanging line 6 and line 7
d. lnterchanging line 7 and line 8

User BlackMael
by
2.8k points

2 Answers

2 votes

Answer:

D. 7 and 8

Step-by-step explanation:

The average only has to be calculated once, after the sum and count values have been finalized.

User Tom Freudenberg
by
3.3k points
3 votes

Answer:

Option d lnterchanging line 7 and line 8

Step-by-step explanation:

This program is expected to calculate the average of all the elements in a list. This is not necessary to include the step average <- sum/count in the for loop. We only need to calculate the average after we get the final sum and count. We don't need to repeatedly calculate the average using the sub-total and current count number. We will only the the final sum and count after completion of the for loop and therefore the step should be placed outside the loop and this can reduce number of calculation operation but produce the same output. The modified program logic is as follows:

Line 1: count ← 0

Line 2: sum ← 0

Line 3: FOR EACH value IN numbers

Line 4: {

Line 5: count ← count + 1

Line 6: sum ← sum + value

Line 7: }

Line 8: average ← sum / count

Line 9: DISPLAY (average)

User Runnerpaul
by
3.6k points