Java program to perform insertion of an element in an array.

Below code in Java is used to perform insertion of an element in an array :

import java.util.Scanner;
 
public class Insertarray
{
    public static void main(String[] args)
    {
        int n,pos,x;
        Scanner s=new Scanner(System.in);
        System.out.println("Enter the number of element in the array");
        n=s.nextInt();
        int a[]=new int[n+1];
        System.out.println("Enter the element");
        for(int i=0;i<n;i++)
        {
            a[i]=s.nextInt();
        }
        System.out.println("Enter the position where you want to inset element");
        pos=s.nextInt();
        pos-=1;
        System.out.println("Enter the element to insert");
        x=s.nextInt();
        for(int i=(n-1);i>=pos;i--)
        {
        a[i+1]=a[i];
        }
        a[pos]=x;
        System.out.println("After the insertion");
        for(int i=0;i<n+1;i++)
        {
        System.out.println(a[i]+"  ");
        }
    }
}   
Thank You.

© Copyright - 2018 - 2021 | All rights reserved at Funda of Web IT