In this tutorial you will learn about the Java Program to Insert Element at Specific Position in Array and its application with practical example.
Java Program to Insert Element at Specific Position in Array
In this tutorial, we will learn to create a Java program that will insert an Element at a Specific Position in an Array using Java programming.
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following Java programming topics:
- Operators in Java Programming.
- Basic Input and Output function in Java Programming.
- Basic Java programming.
- For loop in Java programming.
- Arithmetic operations in Java Programming.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Step 1 :- Initialize the program. Step 2 :- Declaring the variables for the program. Step 3 :- Taking the size of the array. Step 4 :- Taking the extra element's position of the array. Step 5 :- Taking the extra element for the array. Step 6 :- Adding that element in the array. Step 7 :- Printing the array after insertion. Step 8 :- End the program. |
Program description:-
In this program, We will first take the size and the elements of the array. Then We will take the new element and its position from the user. At last, we will add the element in the array and will print that to the user.
With the help of this program, we can insert an Element at a Specific Position in the Array.
Program Code:-
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 33 34 35 36 37 38 39 40 |
import java.util.Scanner; public class Insert_Array { public static void main(String[] args) { //Declaring the required variables for the program. int n, positionn, x; //n = it will hold the input value for size of array Scanner s = new Scanner(System.in); //Taking the size of the array from the user. System.out.print("Enter no. of elements you want in array:"); n = s.nextInt(); int a[] = new int[n+1]; //Taking the element of the array. System.out.println("Enter all the elements:"); for(int i = 0; i < n; i++) { a[i] = s.nextInt(); } //Taking the position of the new element System.out.print("Enter the position where you want to insert element:"); positionn = s.nextInt(); //Taking the new element System.out.print("Enter the element you want to insert:"); x = s.nextInt(); for(int i = (n-1); i >= (positionn-1); i--) { a[i+1] = a[i]; } a[positionn-1] = x; //Printin the array to the user. System.out.print("After inserting:"); for(int i = 0; i < n; i++) { System.out.print(a[i]+","); } System.out.print(a[n]); } } |
Output:-
In the above program, we have first initialized the required variable.
- positionn = it will hold the integer value for the position.
- n = it will hold the integer value.
- i = it will hold the integer value.
Input size and the elements of the array from the user.
Taking the new element and its position from the user to add in the array.
Printing array after adding the element in the array.