Here is a Java program to delete an element from array at any given index. In this java program, given an array of length N, we have to delete an element from array at index i (0 <= i <= N-1). After deletion, the number of elements in array will reduce by one. To delete an element at index i we have to shift all elements from index i+1 to N-1 to previous index.
For ExampleInput Array : [8 4 7 1 9 3 6 4] Deleting 1 at index 3 Output Array : [8 4 7 9 3 6 4]
How to delete an element from an array at given index ?
Let inputArray is an array of length N, and we want to delete an element at index I.
Let inputArray is an array of length N, and we want to delete an element at index I.
- Shift all elements from inputArray[I+1] to inputArray[M-1] to previous index. Move inputArray[j] to inputArray[j - 1], I+1 <= j <= M-1.
- Above step delete inputArray[I] by overwriting it with inputArray[I+1].
- Now, inputArray contains M-1 elements from index 0 to M-2.
Java program to delete an element from array
package com.tcc.java.programs; import java.util.Scanner; public class DeleteArrayElement { public static void main(String[] args) { int count, i, index; int input[] = new int[100]; Scanner scanner = new Scanner(System.in); System.out.println("Enter Number of Elements in Array"); count = scanner.nextInt(); /* * Take array input from user */ System.out.println("Enter " + count + " Numbers"); for (i = 0; i < count; i++) { input[i] = scanner.nextInt(); } System.out.println("Enter Index of Element to be Deleted"); index = scanner.nextInt(); for (i = index; i < count - 1; i++) { input[i] = input[i + 1]; } // decrement size of array count--; System.out.println("Final Array"); for (i = 0; i < count; i++) { System.out.print(input[i] + " "); } } }Output
Enter Number of Elements in Array 8 Enter 8 Numbers 1 2 3 4 5 6 7 8 Enter Index of Element to be Deleted 4 Final Array 1 2 3 4 6 7 8
Recommended Posts