Today we gonna discuss one of the important concept related to the coding interviews .This is frequently asked in the interviews , how to insert a new element inside an array in java with the help of user to input through Scanner Class.
import java.util.Scanner;
class InsertDemo
{
int n,pos,ele,count=0,del;
public void getData()
{
System.out.println("enter the size of array:");
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
int[] arr=new int[n];
for(int i=0;i<n;i++)
{
System.out.println("enter array elements:"+(i+1));
arr[i]=sc.nextInt();
}
System.out.println("array elements are:");
for(int i=0;i<n;i++)
{
System.out.println(arr[i]);
}
System.out.println("enter the new element you want to insert:");
ele=sc.nextInt();
System.out.println("enter the index where you want to insert:");
pos=sc.nextInt();
for(int i=n-1;i>=pos;i--)
{
arr[i]=arr[i-1];
}
arr[pos]=ele;
System.out.println("element inserted successfully");
for(int i=0;i<n;i++)
{
System.out.println(arr[i]);
}
}
}
class Test
{
public static void main(String[] args)
{
InsertDemo i=new InsertDemo();
i.getData();
}
output:
enter the size of array:
5
enter array elements:1
10
enter array elements:2
20
enter array elements:3
30
enter array elements:4
40
enter array elements:5
50
array elements are:
10
20
30
40
50
enter the new element you want to insert:
100
enter the index where you want to insert:
2
element inserted successfully
10
20
100
30
40
Description:
- In the logical part of this program first we will traverse the array from the last index .
- for(int i=n-1;i>index;i--)
- After traverse just swap the index of elements and after then insert your new element
- arr[i]=arr[i+1]
for(int i=n-1;i>=pos;i--)
{
arr[i]=arr[i-1];
}
arr[pos]=ele;
- Element inserted successfully.