Java Program to insert element to an array at specified position
Program
import java.util.Arrays;
import java.util.Scanner;
public class InsertElementsToArrayAtPosition {
public static void main(String[] args) {
int newElement;
int i, j;
int position;
System.out.println("Enter the required size of the array: ");
Scanner reader = new Scanner(System.in);
int size = reader.nextInt();
int inputArray[] = new int[size + 1];
System.out.println("Enter the elements of the array: ");
for (i = 0; i < size; i++) {
inputArray[i] = reader.nextInt();
}
System.out.print("Enter the element which you want to insert: ");
newElement = reader.nextInt();
System.out.print("Enter the position where you want to insert: ");
position = reader.nextInt();
System.out.print("Printing array elements after inserting : ");
for (j = inputArray.length - 1; j > position; j--) {
inputArray[j] = inputArray[j - 1];
}
inputArray[position] = newElement;
System.out.println(Arrays.toString(inputArray));
}
}
Output
javac InsertElementsToArrayAtPosition.java
java InsertElementsToArrayAtPosition
Enter the required size of the array:
3
Enter the elements of the array:
11
22
44
Enter the element which you want to insert: 33
Enter the position where you want to insert: 2
Printing array elements after inserting : [11, 22, 33, 44]