Home > Software engineering >  Subtracting all elements in single array Java
Subtracting all elements in single array Java

Time:09-03

Hi I'm having trouble subtracting one array element to the next element to get the correct answer. The value of the array are given by the user.

Example: If the user wants to input 3 numbers which are 10, 8, 1 10-8-1 = 1

int numberOT = 0;
int total =0;
System.out.println("Enter Number of times: ");
numberOT =in.nextInt();

int number[] = new int [numberOT];



for(int i = 0; i<numberOT; i  )
{
    System.out.println("Enter Number: ");
    number[i] = in.nextInt();
}
for(int t =0; t<number.length-1; t  )
{
  total = number[t] - number[t 1];
}
System.out.println("total: "   total);

CodePudding user response:

Change the 2nd loop to this:

total = number[0];
for (int i=1; i<number.length; i  ) {
    total -= number[i];
}

You want to subtract the remaining array items from the first one. Therefore total in the beginning should be equal to the first item and in the loop subtract each consequent (start from the index 1) item from the total.

Remember the number of items in the array must be equal to or larger than 2.

CodePudding user response:

this line is totally wrong : total = number[t] - number[t 1]; as in the last loop

total = number[1] - number[2] which will be equivalent to total = 8 - 1 = 7 which is totally wrong because you have to accumulate the total variable .

so as mentioned above the full correct answer code is :

    import java.util.Scanner;

    public class Main
    {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);

            int numberOT = 0;
            int total =0;
            System.out.println("Enter Number of times: ");
            numberOT =in.nextInt();

            int number[] = new int [numberOT];

            for(int i = 0; i<numberOT; i  )
            {
                System.out.println("Enter Number: ");
                number[i] = in.nextInt();
            }
            total = number[0];
            for (int i=1; i<number.length; i  ) {
                total = total - number[i];
            }
            System.out.println("total: "   total);

        }
    }

and here is image of the output:

[enter image description here][1]

  • Related