Delete Element from Array
This program deletes an element from a specific position in an array.
Problem Statement
Write a Java program to delete element at index 3 from an integer array.
Source Code
| 1 | public class ArrayDeletion { |
| 2 | public static void main(String[] args) { |
| 3 | int[] arr = {5, 10, 15, 20, 25}; |
| 4 | int pos = 3; |
| 5 | int[] newArr = new int[arr.length-1]; |
| 6 | for(int i=0; i<pos; i++) newArr[i] = arr[i]; |
| 7 | for(int i=pos+1; i<arr.length; i++) newArr[i-1] = arr[i]; |
| 8 | System.out.print("Array after deletion: "); |
| 9 | for(int num : newArr) System.out.print(num + " "); |
| 10 | } |
| 11 | } |
Program Output
Array after deletion: 5 10 15 25
Explanation
A new array newArr with one fewer slot is created; elements before the target position are copied directly, and elements after the position are shifted left, together demonstrating a deletion operation.