I have an array with [25, -6, 14, 7, 100]. The expected output is
JavaScript
x
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
JavaScript
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.
JavaScript
String[] array = [32] // outputs -32
I tried looping through the code like:
JavaScript
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
JavaScript
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;
}