Java program to insert an element in an array or at a specified position. We will discuss a couple of methods on how to insert an element in an array at a specified position. The compiler has been added so that you can execute the programs yourself, alongside suitable examples and sample outputs added. The following program has been added in two different ways as follows:
- Insertion of an element(Standard)
- Insertion of an element(from a specific position of an array)
Insert An Element in Array – Standard
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.util.Scanner; class Insert { public static void main(String[] args) { int len, p,ele; Scanner sc = new Scanner(System.in); System.out.print("Enter length of an array:"); len = sc.nextInt(); int arr[] = new int[len+1]; System.out.println("Enter "+len+" elements:"); for(int i = 0; i < len; i++) { arr[i] = sc.nextInt(); } System.out.print("Enter the element which you want to insert:"); ele = sc.nextInt(); arr[len] = ele; System.out.print("After inserting : "); for(int i = 0; i <len; i++) { System.out.print(arr[i]+","); } System.out.print(arr[len]); } } |
Output:
1 2 3 4 5 6 7 8 |
Enter length of an array:4 Enter 4 elements: 1 2 3 4 Enter the element which you want to insert:5 After inserting : 1,2,3,4,5 |
From Specific Position Of An Array
1) We can insert the element at any position of the array using the index concept.
2) If we want to insert the element in the nth position, then a[n-1]=element to be inserted. i.e. the element will be inserted at the n-1 index of an array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import java.util.Scanner; class Insert { public static void main(String[] args) { int len, p,e; Scanner sc = new Scanner(System.in); System.out.print("Enter length of an array:"); len = sc.nextInt(); int arr[] = new int[len+1]; System.out.println("Enter "+len+" all the elements:"); for(int i = 0; i < len; i++) { arr[i] = sc.nextInt(); } System.out.print("Enter the position where you want to insert an element:"); p = sc.nextInt(); System.out.print("Enter the element which you want to insert:"); e = sc.nextInt(); for(int i = len-1; i >= (p-1); i--) { arr[i+1] = arr[i]; } arr[p-1] = e; System.out.print("After inserting : "); for(int i = 0; i <=len; i++) { System.out.print(arr[i]+","); } } } |
Output:
1 2 3 4 5 6 7 8 9 10 |
Enter length of an array:4 Enter 4 all the elements: 1 2 3 4 Enter the position where you want to insert an element:3 Enter the element which you want to insert:5 After inserting : 1,2,5,3,4, */ |
If you have any doubts or suggestions for the above program leave a comment here.
More Programs: