Replace element in array java – Java Program to Replace Every Array Element by Multiplication of Previous and Next Element

Replace element in array java: In the previous article, we have seen Java Program to Set Positive Elements at Even and Negative at Odd Positions

In this article we are going to see how to replace every array element by product of previous and next element using Java programming language.

Java Program to Replace Every Array Element by Multiplication of Previous and Next Element

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

Let’s see how to replace every array element by product of previous and next element.

 

Method-1: Java Program to Replace Every Array Element by Multiplication of Previous and Next Element By Using an Extra Array

Approach:

  • Create a new array of the size of the original array.
  • Iterate over the new array.
  • At each index, except 0th and last, update the element with the product of the elements at next and previous indices of the original array.
  • If it’s the 0th index, update it with the product of the elements at the 0th and 1st
  • If it’s the last index, update it with the product of the elements at the last and second last indices.

Program:

import java.util.Scanner;
import java.util.Arrays;

public class Main
{
    public static void main(String[] args) 
    {
        // create scanner class object
        Scanner sc = new Scanner(System.in);
        // take input from user for array size
        System.out.print("Enter the size of array: ");
        int n = sc.nextInt();
        // initialize array with size n
        int[] arr = new int[n];
        // take input from user for array elements
        System.out.print("Enter array elements: ");
        for (int i = 0; i < n; i++) 
        {
            arr[i] = sc.nextInt();
        }
        // print original array
        System.out.println("Original array: " + Arrays.toString(arr));
        // replace array elements with multiplication of previous and next
        // elements and print modified array
        //calling the modify() method
        System.out.println("Modified array: " + Arrays.toString(modify(arr)));
    }

    //modify() method
    public static int[] modify(int[] arr) 
    {
        // create new array with size of original array
        int[] arr2 = new int[arr.length];
        for (int i = 0; i < arr.length; i++) 
        {
            // if element is not first or last element
            if (i != 0 && i != arr.length - 1) 
            {
                // replace element with multiplication of previous and next
                // elements
                arr2[i] = arr[i - 1] * arr[i + 1];
            }
            // if element is first element
            else if (i == 0) 
            {
                // replace element with multiplication of next element
                arr2[i] = arr[i] * arr[i + 1];
            }
            // if element is last element
            else 
            {
                // replace element with multiplication of previous element
                arr2[i] = arr[i - 1] * arr[i];
            }
        }
        return arr2;
    }
}
Output:

Enter the size of array: 6
Enter array elements: 1 2 3 4 5 6
Original array: [1, 2, 3, 4, 5, 6]
Modified array: [2, 3, 8, 15, 24, 30]

Method-2: Java Program to Replace Every Array Element by Multiplication of Previous and Next Element By Dynamic Initialization of Array Elements

Approach:

  • First store arr[0] value in variable prev.
  • Update 0th index element with product of (prev value) i.e  0th  and 1st index.
  • Iterate over the array from index 1 to arr.length – 1
  • Inside the loop, store the current element in a curr variable.
  • Update the current element with product of prev and the element at the next index.
  • Then assign the value in curr to prev. As curr holds the actual previous value.
  • Update the last element as the product of prev with itself.

Program:

import java.util.Scanner;
import java.util.Arrays;

public class Main
{
    public static void main(String[] args) 
    {
        // create scanner class object
        Scanner sc = new Scanner(System.in);
        // take input from user for array size
        System.out.print("Enter the size of array: ");
        int n = sc.nextInt();
        // initialize array with size n
        int[] arr = new int[n];
        // take input from user for array elements
        System.out.print("Enter array elements: ");
        for (int i = 0; i < n; i++) 
        {
            arr[i] = sc.nextInt();
        }
        // print original array
        System.out.println("Original array: " + Arrays.toString(arr));
        // replace array elements with multiplication of previous and next
        // elements and print modified array
        //calling modify() method
        System.out.println("Modified array: " + Arrays.toString(modify(arr)));
    }
    
    //modify() method
    public static int[] modify(int[] arr) 
    {

        int prev = arr[0];
        
        //for first elemnt 
        arr[0] = prev * arr[1];
        
        for (int i = 1; i < arr.length - 1; i++) 
        {
            // if element is not first or last element
            if (i != 0 && i != arr.length - 1) 
            {
                // replace element with multiplication of previous and next
                // elements
                int curr = arr[i];
                arr[i] = prev * arr[i + 1];
                prev = curr;
            }

        }
        
        //for last element 
        arr[arr.length - 1] = prev * arr[arr.length - 1];
        return arr;
    }
}
Output:

Enter the size of array: 5
Enter array elements: 1 2 3 4 5
Original array: [1, 2, 3, 4, 5]
Modified array: [2, 3, 8, 15, 20]

Guys who are serious about learning the concepts of the java programming language should practice this list of programs in java and get a good grip on it for better results in exams or interviews.

Related Java Programs:

Leave a Comment