Write a loop that sets each array element to the sum of itself and the next element, except for the last element which stays the same. Be careful not to index beyond the last element. Ex: Initial scores: 10, 20, 30, 40 Scores after the loop: 30, 50, 70, 40 The first element is 30 or 10 20, the second element is 50 or 20 30, and the third element is 70 or 30 40. The last element remains the same.

Respuesta :

Answer:

The solution code is written in Python

  1. numList = [10, 20, 30, 40]
  2. for i in range(0, len(numList) - 1):
  3.    numList[i] = numList[i] + numList[i + 1]
  4. print(numList)

Explanation:

Firstly, create a sample number list, numList (Line 1)

Create a for-loop that will traverse through the array element from 0 till the second last of the element (len(numList) - 1) (Line 3)

Set the current element, numList[i], to the sum of the current element, numList[i] and the next element, numList[i+1]

Print the modified numList (Line 6) and we can see the output as follows:

[30, 50, 70, 40]

ACCESS MORE