The Program in C to delete an element from 1-d sorted array is given below:
#include <stdio.h>
int main() {
int n, pos, i, element;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int a[n];
printf("Enter the elements of the array: ");
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
printf("Enter the element to be deleted: ");
scanf("%d", &element);
pos = -1;
for (i = 0; i < n; i++) {
if (a[i] == element) {
pos = i;
break;
}
}
if (pos == -1) {
printf("Element not found in the array.");
} else {
for (i = pos; i < n-1; i++) {
a[i] = a[i+1];
}
n--;
printf("Array after deletion: ");
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
}
return 0;
}
Output:
Enter the number of elements in the array: 3
Enter the elements of the array: 99
105
999
Enter the element to be deleted: 99
Array after deletion: 105 999
Pro-Tips💡
This program first takes the number of elements in the array and the elements themselves as input.
It then takes the element to be deleted as input, and uses a loop to search for the element in the array.
If the element is found, the position of the element is stored in the variable ‘pos’.
Then using another loop all elements after the element to be deleted are shifted to left by one position, effectively removing the element. Finally, the modified array is printed out.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.