Java Program to Delete an Element from Array at Given Position

  • 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 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 ?
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

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 

Recommended Posts
Java Program to Search an Element in an Array using Linear Search
Java Program to Find Sum of Elements of an Array
Java Program to Merge Two Sorted Arrays
Java Program to Find Average of all Array Elements
Java Program to Insert an Element in Array at Given Position
Java Program to Find Duplicate Elements in an Array
C++ Program to Find Smallest Element in Array
C++ Program to Find Largest Element of an Array
Java Program to Find Largest of Three Numbers
Java Program to Find LCM and GCD of Two Numbers
Java Program to Reverse Array Elements
All Java Programs