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
Original array arr initialized. - New array newArr created with one less space. - Elements before position copied directly. - Elements after position shifted left. - Together demonstrates deletion operation. Conclusion: Shows how arrays can be manipulated to delete elements.