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

Sum:        = 140
Difference: = -90
Product:    = -147000

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

for (int i = 0; i < array.length; i++) {
  System.out.println(" => " + array[I]);
  sum += i;
  product *= i;
}

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.

String[] array = [32] // outputs -32

I tried looping through the code like:

for (int i = 0; i < arrayNumbers.length; i++) {
  System.out.println(arrayNumbers[i] - arrayNumbers[i + 1]);
}

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

Advertisement

Answer

FOUND THE ANSWER

int[] array = {25, -6, 14, 7, 100}

int sum = 0;
int product = 1;
int difference = 0;

for (int i = 0; i < array.length; i++) {
  System.out.println(" => " + array[i]);
  sum += i;
  product *= I;
  if (i == 0)
    difference = i;
  else
    difference -= i;
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement