This C program takes the position as input from the user and deletes the element of array at that position.
In this program, the original array and its size is also entered by the user.
In an array, every element is given certain position which can be used to access or modify the data element at that position. The position is also known as the index. In this code example, we’ll use index to delete an element from the array at desired position.
Program: C program to delete an element from an array at desired position
#include<stdio.h> int main() { int a[50], pos, i, n; //get the size of the array from user printf("Enter no of elements: "); scanf("%d",&n); //get the elements of array from the user printf("\nEnter the elements : "); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("\nEnter the position from where you want to delete element: "); scanf("%d",&pos); if(pos>n) printf("\nWrong input, try again!!!\n"); else { for(i=pos-1;i<n-1;i++) a[i]=a[i+1]; printf("\nUpdated array : "); for(i=0;i<n-1;i++) printf("\n%d",a[i]); printf("\n"); } return 0; }
Output: Delete element from array and print the updated array
Enter no of elements: 7
Enter the elements : 79 45 60 25 102 38 40
Enter the position from where you want to delete element: 5
Updated array :
79
45
60
25
38
40
An element can also be deleted from an array using function. We’ll use the same algorithm to write function to delete an element from the array from desired position.
C program to delete an element from an array using function and pointer
#include<stdio.h> int *delete(int[], int, int); int main() { int a[50], pos, i, n; printf("Enter no of elements: "); scanf("%d",&n); printf("\nEnter the elements : "); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("\nEnter the position from where you want to delete element: "); scanf("%d",&pos); delete(a,n,pos); printf("\nArray after deletion: "); for(i = 0; i < n -1; i++){ printf("\n%d",a[i]); } printf("\n"); return 0; } int *delete(int arr[], int size, int pos){ int i; if(pos>size) printf("\nEnter valid position!!\n"); else { for(i=pos-1;i<size-1;i++) arr[i]=arr[i+1]; } return arr; }
Output:
Enter no of elements: 5
Enter the elements : 23 42 55 97 64
Enter the position from where you want to delete: 3
Array after deletion:
23
42
97
64
That’s it. This is how to delete an element from an array with desired position in C.
Share your code for deletion in an array in the comments.
For more programming articles and code snippets, visit programming articles.