wap in Java to delete an element from an array.
Answers
Answer:Heres's the program.
Explanation:
public class JavaProgram
{
public static void main(String args[])
{
int size, i, del, count=0;
int arr[] = new int[50];
Scanner scan = new Scanner(System.in);
System.out.print("Enter Array Size : ");
size = scan.nextInt();
System.out.print("Enter Array Elements : ");
for(i=0; i<size; i++)
{
arr[i] = scan.nextInt();
}
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)
{
System.out.print("Element Not Found..!!");
}
else
{
System.out.print("Element Deleted Successfully..!!");
System.out.print("\nNow the New Array is :\n");
for(i=0; i<(size-1); i++)
{
System.out.print(arr[i]+ " ");
}
}
}
}
Program:
import java.util.Arrays;
import java.util.Scanner;
public class DeleteElement {
static int[ ] deleteElement(int[ ] array, int position) {
int[ ] newArray = new int[array.length - 1];
// Copying elements before the position
System.arraycopy(array, 0, newArray, 0, position);
// Copying elements after the position
System.arraycopy(array, position + 1, newArray, position, newArray.length - position);
return newArray;
}
public static void main(String[ ] args) {
Scanner sc = new Scanner(System.in);
// Accepting elements into the Array.
System.out.println("Enter the Array elements - ");
int[ ] array = new int[10];
for (int i = 0; i < 10; )
array[i++] = sc.nextInt( );
System.out.println("Array Before - " + Arrays.toString(array));
// Accepting the position of element to be deleted.
System.out.print("Enter index position of the element to be deleted - ");
int position = sc.nextInt( );
array = deleteElement(array, position);
System.out.println("Array After - " + Arrays.toString(array));
}
}
Algorithm:
- Accepting the elements into the array.
- Printing the array before element deletion.
- Accepting the index position of the element to be deleted.
- Copying the portion of array before the delete element position and after it into a new array of length - 1 than the previous.
- Printing the array after element deletion.