To delete an element from an array (in C)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
No comments:
Post a Comment