Beginners Programs :

Java Code Multiply by Length Of Elements In Array | Java Programs

Java Code Multiply by Length Of Elements In Array, Create a function to multiply all of the values in an array by the amount of values in the given array.

For this, we require the length of the array or the total number of elements (n) along with the value of each element in the array (a). To gather this information, we can make use of a well known input class, Scanner class.This class can be used to read inputs from console screen at runtime for any primitive datatype.

To use this, we first have to create an object to instantiate the scanner class and then invoke the nextInt() method to read the length of array followed by traversing through the array and reading each element of the array. nextInt() method is used because, all our input values are of integer type.

We then call the  print() method. This method prints all the array elements by traversing through the end and printing each element in the console screen by using the System.out.print() method. We print the elements just for the clarity of the user.

static void print(int a[],int n) {

for(int i=0;i<n;i++) {

System.out.print(a[i]+” “);



Then, we call the static method (lm). This method consists of the set of statements which enable us to arrive at our desired output. We send array (a) along with length of array (n) as arguments to this method.

In this method, we traverse through the array until the end and multiply each element with the length of the array and store it in the same variable or index.

This is our new resultant array. This is then printed by calling the print() method.

for(int i=0;i<n;i++) {




Our initial array is a[] = { 1, 2, 3, 4, 5} and length of array is 5.

So now, a[0]=1*5=5, a[1]=2*5=10, a[2]=3*5=15, a[3]=4*5=20 and a[4]=5*5=25

Our final output now would be, a[]= { 5, 10, 15, 20, 25}

Output -2:

Here, our initial array is, a[]= { 1, 0, 3, 3, 7, 2, 1 } and length is 7.

We multiply each element with the length of array.

a[0]= 1*7=7, a[1]=0*7=0, a[2]=3*7=21, a[3]=3*7=21, a[4]=7*7=49, a[5]=2*7=14 and a[6]=1*7=7

So, our output array a[] is, { 7, 0, 21, 21, 49, 14, 7}