If you delete any element of the array you can write this code. You will start [position-1] and visit [size-1].
After visiting all elements, you have to decreases the [size--].
for(i=position-1; i<size-1; i++) {
array[i] = array[i+1];
}
size--;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | #include<stdio.h> #define MAX_SIZE 10 int main() {
int array[MAX_SIZE],size,i,position,Length =0;
/* Input size of the array */ printf("Enter the size of the array:\n"); scanf("%d",&size);
/* if MAX_SIZE < new size then overflow condition!*/ Length = sizeof(array)/sizeof(array[0]);
if(Length < size) { printf("overflow condition! Please enter size between 1 to %d", Length); } else {
/* Input elements in array */ printf("Enter %d elements:\n",size);
for(i=0; i<size; i++) { scanf("%d",&array[i]); }
/* Input position to delete */ printf("Enter the deleting position:\n"); scanf("%d",&position);
/* If position of element is not valid */ if(position>size ||position <=0) { printf("Please enter position between 1 to %d", size); return; } else { /* start form position-1 */ for(i=position-1; i<size-1; i++) { array[i] = array[i+1]; } size--;
/* Print array after insert */ printf("Array elements after deleting:\n"); for(i=0; i<size; i++) { printf("%d ",array[i]); } }
}
return 0; }
|
Output
Enter the size of the array:
8
Enter 8 elements:
10 20 30 40 50 60 70 80
Enter the deleting position:
3
Array elements after deleting:
10 20 40 50 60 70 80