Home » Java programs » Java array programs

Java program to delete a specific element from a one dimensional array



In this java program, we are going to learn how to delete an element from a one dimensional array? Here, we have an array and then deleting a given element from array.
Submitted by IncludeHelp, on December 07, 2017

Given an array and an element to delete and we have to delete it from array using java program.

Example:

Input:
Given array (elements will be read in program): 10 20 30 40 50
Enter element to delete: 40
Output:
Array elements after deleting the element: 10 20 30 50

Program to delete an element from an array in java

import java.util.Scanner;

public class ExArrayDelete
{
   public static void main(String args[])
   {
	   // initialize the objects.
       int size, i, del, count=0;
       int arr[] = new int[50];
       Scanner scan = new Scanner(System.in);
	   
       // enter array size.
       System.out.print("Enter Array Size : ");
       size = scan.nextInt();
	   
       // enter elements.
       System.out.println("Enter Array Elements : ");
       for(i=0; i<size; i++)
       {
           arr[i] = scan.nextInt();
       }
	   
       // enter elements which is to be deleted.
       System.out.print("Enter Element to be Delete : ");
       del = scan.nextInt();
       for(i=0; i<size; i++)
       {
           if(arr[i] == del)
           {
               for(int j=i; j<(size-1); j++)
               {
                   arr[j] = arr[j+1];
               }
               count++;
               break;
           }
       }
       if(count==0)
       {
    	   // print if entered element not found.
           System.out.print("Element Not Found..!!");
       }
       else
       {
    	   // element deleted.
           System.out.print("Element Deleted Successfully..!!");
           
           // new array after deletion.
           System.out.print("\nNow the New Array is :\n");
           for(i=0; i<(size-1); i++)
           {
               System.out.print(arr[i]+ " ");
           }
       }
   }
}

Output

Enter Array Size : 10
Enter Array Elements : 
25
36
56
69
98
55
44
75
36
95
Enter Element to be Delete : 75
Element Deleted Successfully..!!
Now the New Array is :
25 36 56 69 98 55 44 36 95 





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions





© https://www.includehelp.com (2015-2018), Some rights reserved.




Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.
Close