Search code examples
javaarraysintdividesubtraction

how do I subract ints from each other in an array Java


I have to write a program where the user inputs 3 numbers into an array and then the output is the numbers subtracted from each other.

I have tried using a for loop for this but it just outputs the numbers added together then turns it negative eg : if i put in the numbers 1,2 and 3 it should output -4 but outputs -6.

this is my code : (the print line part is in another method )

int sub = 0;

for(int j =0; j < numbers.length;j++)
{
    sub -= numbers[j];
}
return sub;

how do I get the numbers to subtract. Also if anyone knows how to get the numbers to divide by each other that would be really helpful : )

Thanks in advance


Solution

  • int sub = numbers[0];
    
    for(int j = 1; j < numbers.length;j++)
    {
        sub -= numbers[j];
    }
    
    return sub;
    

    To divide, use /= instead of -=.