Skip to content
Advertisement

Add/Subtract/etc element by the next element in an array

I have an array with [25, -6, 14, 7, 100]. The expected output is

JavaScript

Basically, the next element is subtracted/added to the current element when looping. That sum and product is easy as I only need to do

JavaScript

The problem is that when I do difference -= i, it gives me -108, which is wrong. And when there is only a single element in the array, it gives me the negative form of the element. e.g.

JavaScript

I tried looping through the code like:

JavaScript

and it gives me Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1

Advertisement

Answer

FOUND THE ANSWER

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement