Here is a java program to insert an element in array at any given index. In this java program, given an array of N elements, we have to insert an element at index i (0 <= i <= N-1) without using extra memory space. After insertion, the number of elements in array will increase by one. To insert an element at index i in array we have to shift all elements from index i to N-1 to next index.

For Example,Input Array : [2 5 3 4 6 1 7]

Inserting 9 at index 4

Output Array : [2 5 3 4 9 6 1 7]

**Algorithm to insert an element in an array**

Let inputArray is an integer array of length N, which contains M (M<N) elements and S is the element that we want to insert at index I.

*Time Complexity : O(n)*

- Move all elements between index I to M-1 to next index(including index I and M-1).
- Move inputArray[j] to inputArray[j + 1], I <= j <= M-1.
- Insert S at inputArray[I].
- Now, inputArray contains M+1 elements from index 0 to M.

## Java program to insert an element in array at given index

In this java program, we first take number of elements in array as input fro user and store it in variable "count". Then we ask user to enter "count" numbers and store it in integer array "input". Then we ask user to enter number to be inserted(num) and at what position(index). By implementing above mentioned algorithm we insert "num" at "index" and print the array on screen using a for loop.

package com.tcc.java.programs; import java.util.Scanner; public class InsertArrayElement { public static void main(String[] args) { int count, i, num, index; int input[] = new int[100]; Scanner scanner = new Scanner(System.in); System.out.println("Enter Number of Elements in Array"); count = scanner.nextInt(); System.out.println("Enter " + count + " Numbers"); for (i = 0; i < count; i++) { input[i] = scanner.nextInt(); } System.out.println("Enter Number to be Inserted"); num = scanner.nextInt(); System.out.println("Enter Index of Insertion"); index = scanner.nextInt(); for (i = count; i > index; i--) { input[i] = input[i - 1]; } // inserting num at position "index" input[index] = num; // increment size of array count++; System.out.println("Final Array"); for (i = 0; i < count; i++) { System.out.print(input[i] + " "); } } }Output

Enter Number of Elements in Array 7 Enter 7 Numbers 1 2 3 4 5 6 7 Enter Number to be Inserted 9 Enter Index of Insertion 4 Final Array 1 2 3 4 9 5 6 7

**Recommended Posts**