Home > Back-end >  Add/Subtract/etc element by the next element in an array
Add/Subtract/etc element by the next element in an array

Time:10-23

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(" => "   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

CodePudding user response:

After some trial and error, I found the answer:

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

int sum = 0;
if (arrayNumbers[0] >= 0) {
  int difference = array[0]   array[0];
} else {
  int difference = array[0] * 2;
}
int product = 1;

for (int i = 0; i < array.length; i  ) {
  sum  = i;
  difference -= i;
  product *= i;
}

System.out.println("Sum:\t\t= "   sum)                 // Sum:        = 140
System.out.println("Difference:\t= "   difference)     // Difference: = -90
System.out.println("Product:\t= "   product)           // Product:    = 1470000

CodePudding user response:

This Exception "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1" is due to the reason that whin i=arrayNumbers.length-1,then in the Code:

the arrayNumbers[i 1] gives an exception as it is accessing the arrayNumbers[arrayNumbers.length];

CodePudding user response:

you are basing you calculation on index while you must base it on array[index]

var sum=0;
var difference=0;
var product=1;

for (int i = 0; i < array.length; i  ) {
  System.out.println(" => "   i);
  sum  = array[i];
  if (i ==0)
    difference =array[i];
  else 
    difference-=array[i];
  product *= array[i];
}
  • Related