Delete from array java – Java Program to Delete an Element from Array at Given Position

Delete from array java: The best and excellent way to learn a java programming language is by practicing Simple Java Program Examples as it includes basic to advanced levels of concepts.

Java Program to Delete an Element from Array at Given Position

  • Java program to delete an element from array at any given index.

How to delete element from array java: 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 Example

Input 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 ?
How to delete array element in java: 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.

Time Complexity : O(n)

Java program to delete an element from array

Java program to delete an element from array

package com.tcc.java.programs;
 
import java.util.Scanner;
 
/**
 * Delete an Element from Array at Given Index
 */
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();
 
        /* Move all elements right of index to left by one position */
        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