Delete an element from an array
The following java program will delete the last element from the array. In the given program, the array contains these elements n[9, 8, 5, 4, 3, 7]. The element (4) having index 3 will be deleted after the execution of the program.
Output
Before Deletion
9 8 5 4 3 7
After Deletion
9 8 5 3 7
So from the above output, we come to know that element 4 has been deleted.
The code is here:-
public class ElementDelArray
{
public static void main(String args[])
{
int n[]={9, 8, 5, 4, 3, 7};
int i, pos, l, s,k;
l=n.length;
s=4;
System.out.println("Before Deletion");
for(i=0; i<l; i++)
{
System.out.print(n[i] + " ");
}
pos = 0;
for(i=0; i<l; i++)
{
if(n[i] == s)
{
pos = i;
break;
}
}
for(i=pos; i<l-1; i++)
{
n[i] = n[i+1];
}
System.out.println("\nAfter Deletion");
for(i=0; i<l-1; i++)
{
System.out.print(n[i] + " ");
}
}
}
In the above program, we first find the position of the element (4), and then from that position, all the elements shifted one by one.
More Java program