Delete an element from Array based on position
In this step, we will write a program in C language that accepts an array of integers, the size of the array, and a position of an element to delete. Then, we will delete the element and print the updated array.
#include <stdio.h>
int main()
{
int arr[100], position, c, n;
printf("Enter the number of elements in array: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for(c = 0; c < n; c++)
scanf("%d", &arr[c]);
printf("Enter the location of the element to delete: ");
scanf("%d", &position);
if (position >= n + 1)
printf("Deletion not possible.\n");
else
for (c = position - 1; c < n - 1; c++)
arr[c] = arr[c+1];
printf("The updated array is: ");
for(c = 0; c < n-1; c++)
printf("%d ", arr[c]);
return 0;
}
Code Explanation:
- We create an integer array
arr[100]
, which can store a maximum of 100 elements.
- We take input integer
n
from the user, which represents the number of elements in the array.
- The for loop is used to accept input from the user using the scanf function into the array
arr
.
- We take the position of the element to be deleted as input from the user.
- We check if the user input position is valid or not; it should be between 1 and n.
- If the position is valid, we place the element left to the position to the place of the deleted element, which is achieved by implementing a loop for moving the element to its left places.
- Finally, we output the updated array using the printf statement.