Nicholas Vera Nicholas Vera - 1 year ago 42
Java Question

Multiplying all values of an array using an enhanced loop? Java

The title pretty much covers it. For some reason this problem is escaping me and I can't find the logical answer to this.


Say I have

int[] values = (2,5,3,2,1,4,6,3,2,1,5,3)

I want to get the product of multiplying all these elements. My textbook asks to do this with an enhanced for loop.

for (int element : values)

My first guess, however, was that it couldn't be done with an enhanced for loop.

Is my textbook just trying to trick me to teach me some sort of lesson?

Answer Source

This can't be done with enhanced for loop. Assume you have an array: (I updated the answer after the OP has updated the question, the update is below).

int[] a = {1,2,3};

When you do:

for(int num : a) {
  num = num*something;

You are actually multiplying another variable (the array won't be affected)..

num in the above example is only a copy of an array element. So actually you are modifying a local variable, not the array itself.

Read this and you'll see that the value in the array is copied into a local variable, and this local variable is used. So this multiplication will not affect the original values of the arrays.


If you want to multiply elements and get the result, you can. Your text book is not trying to trick you. It doesn't ask you to change the values. But to use them in order to do some calculations:

int[] values = {2,5,3,2,1,4,6,3,2,1,5,3};
int result=1;
for(int value : values) {
    result *= value;
System.out.println("The result: " + result); //Will print the result of 2*5*3*2*...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download