Loading
Data-structure-with-JAva-Tutorial

Insertion:


How to insert an element in an array at a specific position?


Program Solution :

package QuipoHouse.ArrayOperations;

import java.util.Scanner;

public class Insertion {

	public static void main(String[] args) { 
	
		// Declaration of Array
		int arr[] = new int[20];
		int i;
		
		// Scanner class for taking values
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the num of element of Array less than 20:");
		int n = sc.nextInt();
		
		// Entering n element in Array
		System.out.println("Enter the element in Array:");
		for (i = 0; i < n; i++) {
			arr[i] = sc.nextInt();
		}
		System.out.println("Enter the element to be inserted:");
		int data = sc.nextInt();
		System.out.println("Enter the Pos where element is to be inserted:");
		int pos=sc.nextInt();
		
		// Shifting of Array
		for (i = n - 1; i >= pos-1; i--) {
			arr[i + 1] = arr[i];
		}
		arr[pos-1] = data;
		n++;          // Increasing the size after shifting

		// Printing the updated Array
		System.out.println("---Element after Insertion---");
		for (i = 0; i < n; i++) {
			System.out.print(arr[i] + " ");
		}
	}

}

Output:

Enter the num of element of Array less than 20:
6
Enter the element in Array:
1
2
3
4
5
6
Enter the element to be inserted:
10
Enter the Pos where element is to be inserted:
5
---Element after Insertion---
1 2 3 4 10 5 6