How to insert a value to Nth index of array in Java? |EasyCoding45

How to insert a value to Nth index of array in Java?


In This Tutorial we are going to learn How to insert a value to Nth index of array in Java?


Note :-

  • Array index starts from 0.

Program :-(How to insert a value to Nth index of array in Java?)


import java.util.*;

class array

{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter Limit for array :");

int lim=sc.nextInt();

int arr[]=new int[lim+1];
System.out.println("Enter "+lim+" Element in an Array ");

for(int i=0;i<lim;i++)
{
arr[i]=sc.nextInt();
}
System.out.println("Enter the position you want to insert Element :");

int pos=sc.nextInt();
if(pos>lim ||pos<= -1)
{
System.out.println("Position is out of range :\n Try Again!!!!!");
}
else
{
System.out.println("Enter the Element You want to insert :");

int num=sc.nextInt();

for(int i = (lim-1); i >= (pos-1); i--)
{
arr[i+1] = arr[i];
}
arr[pos-1] = num;

for(int i=0;i<=lim;i++)
{
System.out.println("Elements are :"+arr[i]);
}
}
}
}


Output :--



Comments