Loading
Deletion -tutorial
Deletion in arrays refers to removing an element from a specified position or by its value. When an element is deleted, the remaining elements are shifted to maintain continuity.

There are two main types of deletion in Java arrays:


1. Delete by Index Position

In this method, an element is removed from a specified index (position). After deletion, all subsequent elements are shifted one position to the left.


Example: Deleted by Index

package QuipoHouse.ArrayOperations;

import java.util.Scanner;

public class Deletion {

    public static void main(String[] args) {
        int arr[] = new int[20];
        int i;

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number of elements (less than 20):");
        int n = sc.nextInt();

        System.out.println("Enter " + n + " elements:");
        for (i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }

        System.out.println("Enter the position to delete (1-based index):");
        int pos = sc.nextInt();

        // Shifting elements left
        for (i = pos - 1; i < n - 1; i++) {
            arr[i] = arr[i + 1];
        }
        n--;  // Decrease the size of array

        System.out.println("--- Elements after Deletion ---");
        for (i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

Output:

Enter the number of elements (less than 20):
5
Enter 5 elements:
1
2
3
4
5
Enter the position to delete (1-based index):
5
// --- Elements after Deletion ---
1 2 3 4



2. Delete by Element Value

This method removes an element by value, not position. It searches for the value, then shifts elements after it to the left.


Example: Delete by Value

package QuipoHouse.ArrayOperations;

import java.util.Scanner;

public class Deletion {

    public static void main(String[] args) {
        int arr[] = new int[20];
        int i;

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number of elements (less than 20):");
        int n = sc.nextInt();

        System.out.println("Enter " + n + " elements:");
        for (i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }

        System.out.println("Enter the element to delete:");
        int data = sc.nextInt();

        for (i = 0; i < n; i++) {
            if (arr[i] == data) {
                for (int j = i; j < n - 1; j++) {
                    arr[j] = arr[j + 1];
                }
                n--;
                break; // delete only first occurrence
            }
        }

        System.out.println("--- Elements after Deletion ---");
        for (i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

Output:

Enter the number of elements (less than 20):
5
Enter 5 elements:
4
9
6
5
2
Enter the element to delete:
6
// --- Elements after Deletion ---
4 9 5 2