Explore Java

Be Social. Be Updated.

  • Stumble
  •   
  •   

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;

0 comments:

About This Blog

This blog contains Java Tutorials, Code Samples,demonstrating several concepts in Java. All the code samples are well tested by a team of experts and hence there will be no programmatical errors. We are seamlessly thriving in making the tutorials easier for beginners.

About the Author

was a software and technology enthusiast. He is a 12th grade student and a part time blogger with extreme love in Java programming.Follow him on Google+ and Twitter or befriend him on Facebook and also on