Q:

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

belongs to collection: Java Array Programs

0

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

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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 

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to print EVEN and ODD elements from a... >>
<< Java program to move all zero at the end of the ar...