Java Program to Replace Each Element of the Array with Product of All Other Elements of the Array

In the previous article, we have seen Java Program to Find the Length of an Array

In this article we are going to see how we can replace the elements of an array with the product of all other elements using Java programming language.

Java Program to Replace Each Element of the Array with Product of All Other Elements of the Array

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Method-1: Java Program to Replace Each Element of the Array with Product of All Other Elements of the Array By Static Initialization of Array Elements

Approach:

  • Take an array with elements in it.
  • Print the array elements.
  • Find the product of all elements by iterating using a for loop.
  • Divide individual array elements by the product and store the resultant at that location.
  • Print the new array.

Program:

import java.util.Arrays;
public class array
{
    public static void main(String args[])
    {
        // Creating the array
        int arr[] = {1,2,3,4};

        // Prints the array elements
        System.out.println("The array elements are"+Arrays.toString(arr));
        // Stores the product of all elements in the array
        int product = 1;        
        for(int i:arr)
        {
            product*=i;
        }

        // Divides and replaces the array elements with the product of remaining elements
        for(int i=0;i<arr.length;i++)
        {
            arr[i] = product/arr[i];
        }

        System.out.println("The array elements after replacement"+Arrays.toString(arr));
    }
}

Output:

The array elements are[1, 2, 3, 4]
The array elements after replacement[24, 12, 8, 6]

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

Related Java Programs: