Skip to content

Instantly share code, notes, and snippets.

@mbalayil
Created May 18, 2011 11:40
Show Gist options
  • Save mbalayil/978420 to your computer and use it in GitHub Desktop.
Save mbalayil/978420 to your computer and use it in GitHub Desktop.
To delete an element from an array
/**
* 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment