We start by initializing the size of the array, which will store the values to delete. We then start the loop that iterates through the array elements and looks to see if they’re to be deleted. When a value matches the criteria that we specified for the array element to be removed from the array, we replace the old value with the new value.
C Program for Deleting the Array
Here is the C program Deleting the Array. The procedure is simply the reverse, in other words, all the elements from the bottom of the array will be copied one place up to replace the element that will deleted.
#include
void main()
{
int p[100],i,n,a;
printf("Enter the length of the array: ");
scanf("%d",&n);
printf("Enter %d elements of the array \n",n);
for(i=0;i<=n-1;i++)
scanf("%d",&p[i]);
printf("\nThe array is:\n");\
for(i=0;i<=n-1;i++)
printf("%d\n",p[i]);
printf("Enter the position/location to delete: ");
scanf("%d",&a);
a--;
for(i=a;i<=n-2;i++)
{
p[i]=p[i+1];
/* All values from the bottom of the array are shifted up till
the location of the element to be deleted */
}
p[n-1]=0;
/* The vacant position created at the bottom of the array is set to
0 */
printf("Array after deleting the element is\n");
for(i=0;i<= n-2;i++)
printf("%d\n",p[i]);
}
As a programming exercise, you can also write a program that deletes a given array. The program can work as follows:
- Create an array with two values.
- Read the elements of the array (0, 0, 1, 2, 3, 4).
- The user should enter the size of the array (number of elements) and the index (number) of the element to delete.
- The program should then delete the given element of the array.
- The program should then print the remaining elements of the array.