3

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);
2
  • 4
    Have you tried using "-=" instead of "+="? Commented Jan 20, 2017 at 18:06
  • Your example gives special treatment to the first element. Is that right? Did you mean 1-2-3-4-5? Or did you mean -1-2-3-4-5 (starting with the first element vs. starting with 0)? Commented Jan 20, 2017 at 18:42

6 Answers 6

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

With IntStream and a bit of functional programming

import java.util.Arrays;
import java.util.stream.IntStream;
int myArray[] = {1,2,3,4,5};
int sum = IntStream
          // get all the indices
          .range(0, myArray.length) 

          // for the 1st element use the +ve sign 
          // and for the rest use -ve sign: so it 
          // will generate 1,-2,-3,-4,-5
          .map(i -> i == 0? myArray[i] : -myArray[i]) 

          // add the generated elements using map: 1-2-3-4-5
          .sum(); 

System.out.println(sum); // -13

1 Comment

@soundslikeodd added exlanation, hope that makes it clear.
0

You should start with a the sum at index 0 and then call -= to all the other elements. currently you are doing index - (index -1) which will fail since you don't check for out of bounds. Also the math will be wrong in your current implementation because you use values to subtract twice instead on once.

Take this array with your subtraction method A[1, 2, 3, 4]

sum = 0;
sum += 1 - 2;
sum is -1; (Correct)
sum += 2 - 3;
sum is (-1 + -1) = -2 (Wong, should be -4)
sum += 3 - 4;
sum is (-2 - 1) = -3 (Wrong should be -8)
sum += 4 - A[4] (ERROR index out of bounds)

Here is the implementation that subtracts the values once

if (operator == '-'){
  sum = intArray.length > 0 ? intArray[0] : 0;
  for ( int j = 1; j < intArray.length; j++ ) {
    sum -= intArray[j]; 
  }
}

1 Comment

i was in the middle of explaining it @soundslikeodd
0

We have to take the first value in the array, and then subtract or add the remaining values from and to it depending on the operator. This is done as shown below:

int sum, dif;
if(intArray.length >= 1){
  sum = intArray[0];
  dif = intArray[0];
}
if (operator == '+'){
   if(intArray.length > 1){
     for ( int j = 1; j < intArray.length; j++ ) {
       sum += intArray[j]; 
     }
   }
   System.out.println("The sum is = " + sum);
}
if (operator == '-'){
  if(intArray.length > 1){
    for ( int j = 1; j < intArray.length; j++ ) {
      dif -= intArray[j]; 
    }
  }
  System.out.println("The difference is = " + dif);
}

Comments

0

You always do a positive sum += on operator -. But how about using the Stream-API instead?

IntStream.of(1, 2, 3, 4, 5)
         .reduce(operatorFunction('-'))
         .ifPresent(System.out::println);

with the following IntBinaryOperator-returning function:

static IntBinaryOperator operatorFunction(char operator) {
  if (operator == '-') {
    return (int1, int2) -> int1 - int2;
  }
  return (int1, int2) -> int1 + int2;
}

which prints -13 as you would expect. This is all you need. Note that you could also use IntStream.sum to achieve a simple sum. With the operatorFunction however you could also add * or ÷ later if you wish.

Another way to write the above code (with intermediate values):

int[] yourInputArray = {1, 2, 3, 4, 5};
char operator = '-';
OptionalInt = Stream.of(yourInputArray)
                    .reduce(operatorFunction(operator));

From here you can call orElse(0) or throw an exception with orElseThrow(() -> ...), etc. Just have a look at the OptionalInt-javadoc for your options. As soon as you move away from the primitive int you may want to exchange the code by using Stream, BinaryOperator<Integer> and Optional<Integer>.

By the way, there is also an IndexOutOfBoundException in your current code. But why messing with indexes and arrays, if you can use Streams and so few lines of code?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.