To insert the given element at a given location in an array using java, We have to shift the elements toward the right till we reach the index. This is necessary to free the index to insert the element.
Inserting at a given location and given index is different. In location count will start from 1 but in index count will start from 0.
For Example:
Suppose we have an array arr=[2, 3, 4, 5, 6, 7]
Now we have to insert element 9 at index 2
So our new array will become arr=[2, 3, 9, 4, 5, 6, 7]
Program : Java program to insert element at given index in array
- In the below program to insert element at a given index, first we have to shift array elements towards the right up to given index number.
- It will free the index where we have to insert the element.
- After shifting towards right, we can insert the element at given location and print the array to see updated array.
import java.util.*;
public class Main
{
public static void main(String[] args) {
int loc;
Scanner sc = new Scanner(System.in);
System.out.println("Java Program to insert element at given index of Array");
System.out.print("Enter the size of array: ");
int size = sc.nextInt();
int arr[] = new int[size+1];
for(int i=0; i<size; i++) {
System.out.print("Please give value for index "+ i +" : ");
arr[i] = sc.nextInt();
}
System.out.print("Enter the index where you want to insert:");
loc = sc.nextInt();
for (int i = size-1; i >= loc; i--){
arr[i+1] = arr[i];
}
System.out.print("Enter the element to insert at index "+loc+" : ");
arr[loc] = sc.nextInt();
System.out.println("Array After Inserting "+ arr[loc] +" at index "+loc+" : ");
for(int i=0; i<size+1; i++)
{
System.out.print(arr[i]);
}
}
}
Output