Deletion
Deletion is the operation used to delete the element from the given Array.
It is done in two ways
- By Index number
- By Element
1.By Index Number: Deletion is done through the index number.
Program Solution :
package QuipoHouse.ArrayOperations;
import java.util.Scanner;
public class Deletion {
public static void main(String[] args) {
int arr[] = new int[20];
int i;
// Scanner class for taking values
Scanner sc = new Scanner(System.in);
System.out.println("Enter the num of element of Array less than 20:");
int n = sc.nextInt();
// Entering n element in Array
System.out.println("Enter the element in Array:");
for (i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
System.out.println("Enter the Pos where element is to be deleted:");
int pos = sc.nextInt();
// Shifting of Array
for (i = pos - 1; i <= n - 1; i++) {
arr[i] = arr[i + 1];
}
n--; // Decreasing the Size after shifting
// Printing the updated Array
System.out.println("---Element after Deleted---");
for (i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
Output:
Enter the num of element of Array less than 20:
5
Enter the element in Array:
1
2
3
4
5
Enter the Pos where element is to be deleted:
5
---Element after Deleted---
1 2 3 4
2.By Element:
Program Solution :
package QuipoHouse.ArrayOperations;
import java.util.Scanner;
public class Deletion {
public static void main(String[] args) {
int arr[] = new int[20];
int i;
// Scanner class for taking values
Scanner sc = new Scanner(System.in);
System.out.println("Enter the num of element of Array less than 20:");
int n = sc.nextInt();
// Entering n element in Array
System.out.println("Enter the element in Array:");
for (i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
System.out.println("Enter the element to be deleted:");
int data = sc.nextInt();
// Shifting of Array
for (i = 0; i < n; i++) {
if (arr[i] == data)
for (int j = i; j < n; j++) {
arr[j] = arr[j + 1];
}
}
n--; // Decreasing the Size after shifting
// Printing the updated Array
System.out.println("---Element after Deleted---");
for (i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
Output:
Enter the num of element of Array less than 20:
5
Enter the element in Array:
4
9
6
5
2
Enter the element to be deleted:
6
---Element after Deleted---
4 9 5 2