Java program to insert an element into the array | JAVA POINT

Write a Java program to insert an element into the array.





PROGRAM :


import java.util.*;
class arrinsert
{  
 public static void main(String[] args)
 {
  int n,pos,x;


  Scanner sc=new Scanner(System.in);
  System.out.print("\nEnter size of array : ");
  n=sc.nextInt();


  int a[]=new int[n+1];


  System.out.print("\nEnter all the elements of array : \n");
  
  System.out.println();


  for(int i=0; i<n; i++)
  {
   a[i]=sc.nextInt();
  }


  System.out.println("\nBefore insertion the array is :");


  for(int i=0; i<n; i++)
  {
   System.out.print(a[i]+" ");
  }


  System.out.println();


  System.out.print("\nEnter the position where you want to insert the element: ");
  pos=sc.nextInt();


  System.out.print("\nEnter the element you want to insert : ");
  x=sc.nextInt();


  for(int i=(n-1); i>=(pos-1); i--)
  {
   a[i+1]=a[i];
  }
  a[pos-1]=x;


  System.out.println("\nAfter insertion");


  for(int i=0; i<n; i++)
  {
   System.out.print(a[i]+",");
  }
  System.out.print(a[n]);
 }
}


/*

Output :


Enter size of array : 5

Enter all the elements of array : 

4 6 2 6 7 

Before insertion the array is :
4 6 2 6 7 

Enter the position where you want to insert the element: 3

Enter the element you want to insert : 8

After insertion
4,6,8,2,6,7

*/