Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add and subtract values from a single array Java

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);
like image 900
Stack John Avatar asked May 16 '26 22:05

Stack John


2 Answers

//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

like image 161
shashwatZing Avatar answered May 18 '26 11:05

shashwatZing


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];

like image 31
Rushabh Oswal Avatar answered May 18 '26 10:05

Rushabh Oswal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!