JAVA program to delete an element from an array

JAVA program to delete an element from an array from a specified location/position

This JAVA program is to delete an element from an array from a specified location/position.

For example, if an array a consists of elements a={71,82,21,33,9} and if we want to delete element at position 3 then the new array would be a={71,82,21,9} (as array starts from index 0).

Logic

We start to iterate from the position from which we want to delete the element. The reason for this is so that all the elements after the element which is deleted will be shifted by one place towards the left.

Dry Run of the Program

Take input array ‘a’ and no of elements(n) as 5

Let us take elements for array a={7,8,12,3,9}.

Let us delete an element from the array ,which is at position 3.

1st iteration  for(i=pos;i<n-1;i++)  i.e.  for(i=3;i<5-1;i++)  i.e.  for(i=3;=3<4;i++)

a[i]=a[i+1] i.e. a[3]=a[3+1] i.e. a[3]=a[4] i.e. a[3]=9

Now we move out of the for loop as i will be 4 which is not less than n-1(4).

n=n-1 i.e. n=5-1 i.e n=4 //We are decreasing the no of elements

Hence our new array would be a={7,8,12,9}.

Program

import java.util.*;

class arr4
{  
	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		
	        int i,n,pos;
		
		System.out.println("Enter the number of elements:") ;
 		n = sc.nextInt();
		int[] a = new int[n];
 
    		System.out.println("Enter the elements") ;
    		for(i=0;i<n;i++)
    		{
        		a[i] = sc.nextInt();
    		}
		
    			
		System.out.println("Enter the position of the number which is to be deleted");
 		pos = sc.nextInt();
		   		
		for(i=pos;i<n-1;i++)
	    	{
        		a[i]=a[i+1];
    		}
    		n=n-1;
    		
		System.out.println("\nOn deleting new array we get is\n");
    		for(i=0;i<n;i++) 
    		{
        		System.out.println("a["+i+"] = "+a[i]);
    		}
	}
}

Output

Share Me!