This is a Java Program to Delete the Specified Integer from an Array.
Enter size of array and then enter all the elements of that array. Now enter the element you want to delete. We first find the location of that element and then shift the positions of all the elements after the element to be removed by one.
Here is the source code of the Java Program to Delete the Specified Integer from an Array. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
import java.util.Scanner;
public class Delete
{
public static void main(String[] args)
{
int n, x, flag = 1, loc = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
System.out.print("Enter the element you want to delete:");
x = s.nextInt();
for (int i = 0; i < n; i++)
{
if(a[i] == x)
{
flag =1;
loc = i;
break;
}
else
{
flag = 0;
}
}
if(flag == 1)
{
for(int i = loc+1; i < n; i++)
{
a[i-1] = a[i];
}
System.out.print("After Deleting:");
for (int i = 0; i < n-2; i++)
{
System.out.print(a[i]+",");
}
System.out.print(a[n-2]);
}
else
{
System.out.println("Element not found");
}
}
}
Output:
$ javac Delete.java $ java Delete Enter no. of elements you want in array:5 Enter all the elements: 3 5 8 1 4 Enter the element you want to delete:5 After Deleting:3,8,1,4
Sanfoundry Global Education & Learning Series – 1000 Java Programs.
advertisement
advertisement
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
Related Posts:
- Practice Programming MCQs
- Practice BCA MCQs
- Check Java Books
- Check Programming Books
- Apply for Java Internship