PROGRAM 2
QUESTION
Write a Java program to insert an element (specific position) into an array.
AIM
To write a Java program to insert an element at a specific position into an array.
ALGORITHM
Step 1: Start the program.
Step 2: Declare an integer array arr with space for 6 elements.
Step 3: Initialize the first 5 elements of the array with values:
arr[0] = 10, arr[1] = 20, arr[2] = 30, arr[3] = 40, arr[4] = 50
Step 4: Declare a variable element and assign the value to be inserted.
Step 5: Declare a variable position and assign the index where the element should be inserted.
Step 6: Shift all elements from index 2 to position towards the right by one position to make
space for new element:
Run a loop from i = 2 down to position and set
arr[i + 1] = arr[i]
Step 7: Insert the new element at the desired position:
arr[position] = element
Step 8: Print all the elements of the updated array using a loop.
Step 9: End the program.
CODE
public class InsertSimple {
public static void main(String[] args) {
int[] arr = new int[6];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
int element = 25;
int position = 2;
// shift elements right from position
for (int i = 4; i >= position; i--) {
arr[i + 1] = arr[i];
}
// insert the element at the given position
arr[position] = element;
// to print the updated array
for (int i = 0; i < 6; i++) {
System.out.print(arr[i] + " ");
}
}
}
RESULT
The program displays the updated array, which includes the newly inserted element in the
correct position, while preserving the order of the other elements.
OUTPUT
10 20 25 30 40 50