If a user wants to insert an element in run time in a given location this blog will help you to do so. In the below code user is first asked the size of the array using Scanner class in java and after that, we will increase our array size by one, and then you have to enter the element of the array. Then you will be asked to enter the index to add the element in array and the element.
After this, we come to the main logic of the program where we run the for loop from the last index of array and start swapping the element i.e. last to last -1 then last, last-2 to last -1. In this way, we will move to our index position and finally we will swap our index-1 with index and by that our index will became empty and we will place our inserted item into that index location.
import java.util.Scanner;
class Myfirst {
public static void main(String[] args) {
int size, loc, item, i;
Scanner sc = new Scanner(System.in);
System.out.println("enter the size of arrray");
size = sc.nextInt();
int a[] = new int[size + 1];
System.out.println("enter array element");
for (i = 0; i < size; i++) {
a[i] = sc.nextInt();
}
System.out.println("enter the location to add");
loc = sc.nextInt();
System.out.println("enter the item to add");
item = sc.nextInt();
for (i = size; i > loc; i--) {
a[i] = a[i - 1];
// System.out.println(a[i]);
}
a[loc] = item;
size++;
for (i = 0; i < size; i++) {
System.out.println(a[i]);
}
}
}
Conclusion
We have finally understood in this blog how we can enter our given element in our specific location.