Wednesday, May 18, 2011

Program to delete an element from an array in C

To delete an element from an array (in C)

/**
* Program to delete an element from an array
**/
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int *array, size;
int e, i, pos;
printf("\nEnter the size of the array : ");
scanf("%d", &size);
array = malloc(size * sizeof(int));
printf("\nEnter the elements of the array : ");
for(i = 0; i < size; i++)
scanf("%d",&array[i]);
printf("\nEnter the element to be deleted : ");
scanf("%d", &e);
printf("\n\nOriginal array size : %d", size);
printf("\nOriginal array :\n");
for(i = 0; i < size; i++)
printf("%d ",array[i]);
/* Find out position of 'e' in the array */
for(pos = 0; pos < size; pos++)
if(array[pos] == e)
break;
/* Shift the array elements backwards from 'pos' */
for(i = pos; i < (size - 1); i++)
array[i] = array[i + 1];
array = realloc(array, (size - 1) * sizeof(int));
/* Print updated array */
printf("\n\nThe updated array size : %d", (size - 1));
printf("\nThe updated array :\n");
for(i = 0; i < (size - 1); i++)
printf("%d ", array[i]);
return 0;
}
Written by

No comments:

Post a Comment