#loop to subtract, multiply, divide elements in an array

12 messages · Page 1 of 1 (latest)

tall mantle
#

hello, like in the title I can't answer this question by myself or searching online.
i create this beginner program, for learning:

  • how many elements do you want to operate? x
    -write down the x elements, i will show you sum, subtraction product and division.
    like 10,3,2
    sum of them is = 10 + 3 + 2 = 15
    subtraction is = 10 - 3 - 2 = 5
    product = 10 * 3 * 2 = 60
    division = 10 / 3 / 2 = 1 (int)

i did sum like this:

System.out.print("How many elements you want to treat? ");
int elementi = input.nextInt();
int[] array = new int[elementi];
System.out.println("Enter the elements to treat: ");
for (int i = 0; i < elementi; i++)
{
array[i]=input.nextInt();
}
System.out.println("arraylength is: " + array.length);
int sum = 0;
for (int i = 0; i < array.length; i++)
{
sum = sum + array[i];
}

but i can't understand the cycle for subtraction product and division.
thanks for your help

stuck cedarBOT
#

Hey, @tall mantle!
Please remember to /close this post once your question has been answered!

tall mantle
#

for subtraction i think that i need some sort of:

#

int minus = 0

for (int i = 0; i < array.length; i++)
{
minus = array[0] - all the other elements in sequence

#

but i can't code it properly, neither for product and division... imagine for module, lol

tall mantle
#

noone?

open pasture
#

@tall mantle for subtraction you probably would want to start with
int difference = array[0];
and then do
for(int i = 1; i < array.length; i++) difference -= array[i];
And multiplication should be analogous to addition, and division should be analogous to subtraction

lone kestrel
#

me personally, I'd be that odd ball that uses regex

#

you'd get a string called expression and that would be a field. Then another field which is a string array that "tokenizes" every character. Then another string called coverted expresion that the string array spits into

#

so you pass in a expression. Goes to the token array where its separated with a regex. Then you pass it to the converted expression field. Think that'd be about 20 lines of code.

tall mantle
#

Thanks, already solved. And already did another program that convert from decimal to binary. Keep studing!