I am having trouble subtracting values from a single array. If I have the numbers 1, 2, 3, 4, 5 stored in an array, how can I find the difference?
For example 1-2-3-4-5 = -13
I know how to sum the values of an array but having trouble subtracting one array element from the next to get the correct answer.
int sum = 0;
if (operator == '+'){
for ( int j = 0; j < intArray.length; j++ ) {
sum += intArray[j];
}
}
if (operator == '-'){
for ( int j = 0; j < intArray.length; j++ ) {
sum += intArray[j] - intArray[j+1] ;
}
}
System.out.println("The answer is " + sum);
//This is a pretty simple way to solve it
public class Minimize {
public static int substractArrayValues(int [] q){
int val=0;
for (int i=0; i<q.length; i++){
if (i==0){
val=q[i];
}
else {
val=val-q[i];
}
}
return val;
}
public static void main(String[] args) {
int [] q={1,2,3,4,5};
System.out.println(substractArrayValues(q));
}
}
This will print -13
I assume you want to subtract 1-2-3-4-5 which is equal to -13.
So here comes your mistake sum+=intArray[j] - intArray[j+1] ;
Operation:-
Iteration 1:- sum=-1 which is (1-2) sum=-1
Iteration 2:sum=sum+(2-3) which is (-1+2-3) sum=-2
Iteration 3:sum=sum+(3-4) which is (-2+3-4) sum=-3
Iteration 4:sum=sum+(4-5) which is (-3+4-5) sum=-4
Iteration 5:sum=sum+(5-Garbage value or indexoutofbound exception)
sum=garbage value
Try using sum-=intArray[j];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With