Description
* Deletion of element from an array is to remove element from exiting array. * To delete element at the end just decrement upper bound to 1. * If delete an element at particular position, decrement the index of all elements by 1 which is right to position of element to be deleted then delete element at that position.
C/C++
/* C program to Delete element in an array*/ //Save it as DeleteElementGivenLocation.c #include<stdio.h> int main(){ int i, n, pos; printf("Enter the size of array : "); scanf("%d",&n); int arr[n]; printf("Enter the elements of the array : "); for (i = 0; i < n; i++) { scanf("%d",&arr[i]); } printf("Enter the position of elements to be deleted : "); scanf("%d",&pos); /* Execute a loop to move all elements left by 1 position having index greater than position where to delete element */ for(i=pos;i<n-1;i++) { arr[i] = arr[i+1]; } // Finally print new array after deletion of new element printf("\nThe new array is : "); for(i=0;i<n-1;i++) { printf("%d ", arr[i]); } return 0; }
Input: Enter the size of array : 5 Enter the elements of the array : 16 25 29 37 55 Enter the position of elements to be deleted : 2 Output: The new array is : 16 25 37 55
Java
/* Java program to Delete element in an array*/ //Save it as DeleteElementGivenLocation.java import java.io.*; import java.util.Scanner; public class DeleteElementGivenLocation { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the size of array : "); int n = scanner.nextInt(); int arr[] = new int[n]; System.out.println("Enter the elements of the array : "); for (int i = 0; i < n; i++) { arr[i] = scanner.nextInt(); } System.out.println("Enter the position of elements to be deleted : "); int pos = scanner.nextInt(); /* Execute a loop to move all elements left by 1 position having index greater than position where to delete element */ for(int i=pos;i<n-1;i++) { arr[i] = arr[i+1]; } // Finally print new array after deletion of new element System.out.println("\nThe new array is : "); for(int i=0;i<n-1;i++) { System.out.print(arr[i]+" "); } } }
Input: Enter the size of array : 5 Enter the elements of the array : 16 25 29 37 55 Enter the position of elements to be deleted : 2 Output: The new array is : 16 25 37 55
Related Programs
1) Insert a number in an array sorted in ascending order2) Program to insert a number at given position of an Array
3) Program to delete an element from an array sorted in ascending order
4) Program to merge two sorted arrays
5) Program to swap maximum and minimum element of Array
6) Program to Rearrange an array such that arr[i]=i
7) Program to Find the smallest missing number
8) Program to Find K largest elements from array
9) Program to make pair of elements alternatively
10) Remove Duplicate Elements From Array