Multiply Elements in Array

An example on multiplying all elements in array in Java.

Example



class MultiplyElements
{
public static void main(String args[])
{
int a[]={5,8,6,2,8};
System.out.println("The product is "+multiply(a));
}
public static int multiply(int a[])
{
int prod=1;
for(int k:a)
{
prod*=k;
}
return prod;
}
}

Output



The product is 3840


Analysis


prod*=k means prod=prod*k; where k represents every element in array a till the loop ends. For a better understand, the value of k at first (at the first execution of the loop) is a[0]=5 then, it is a[1]=8 and so on.

The product is 1 initially because, multiplying any number with 1 gives that number only.

The loop is executed 5 times, because there were 5 elements in the array.

prod*=k; is considered for analysis.

1=1*5; => prod=5;
5=5*8; => prod=40;
40=40*6; => prod=240;
240=240*2; => prod=480;
480=480*8; => prod=3840;

return prod; => return 3840;

No comments: