Java Program to Delete Element of Array At Given Location

In this tutorial, we will learn writing Java program to delete an element of an array at given index and print the updated array. Our program will delete the element from the position specified by the user from the given array.

For Example

Case 1: if the given array is [1, 2, 3, 4] and the user gives input 3 to remove element at position 2.

              The output should be [1, 2, 4].

Case 2: if the given array is {9, 2, 4, 8} and the user gives input 4 to remove element at position 4.

          The output should be [9, 2, 4].

Java Program to Delete Element of Array At Given Location

import java.util.*;  
public class Main
{
	public static void main(String[] args) {
		int loc;
		Scanner sc = new Scanner(System.in);
		System.out.println("Java Program to delete element from given index");
        System.out.print("Enter the size of array: ");
        int size = sc.nextInt();
        int arr[] = new int[size];
        for(int i=0; i<size; i++) {
            System.out.print("Please give value for index "+ i +" : ");
            arr[i] = sc.nextInt();
        }
        System.out.println("Enter the index to delete element :");
        loc=sc.nextInt();
        if(loc<=size-1){
            for (int i = loc; i <size-1; i++){
                arr[i] = arr[i+1];
            }
            size--;
            }else{
            System.out.print("index not available");
            System.exit(0);
        }
        System.out.println("Elements after deleting at index "+loc+" are:");
        for(int i=0; i<size; i++)
        {
            System.out.print(arr[i]+"\t");
        }
	}
}

Output

Java Program to delete element from given index
Enter the size of array: 5
Please give value for index 0 : 1
Please give value for index 1 : 2
Please give value for index 2 : 3
Please give value for index 3 : 4
Please give value for index 4 : 5
Enter the index to delete element :
2
Elements after deleting at index 2 are:
1       2       4       5

Explanation

From the input array [1, 2, 3, 4, 5] user input 2, to remove the element at position 2 in the array. Our program will iterate till position 2 in the array and removes the element using statement arr[i] = arr[i+1]. And then returns the new updated array as the output of the program.

So After deleting element at index 2, output will be [1, 2, 4, 5]

What did you think?

Similar Reads

Hi, Welcome back!
Forgot Password?
Don't have an account?  Register Now