Delete An Element From Any Array C Code - Coding Bot

Like Us On Facebook

Follow Us On Twitter

Drop Down Menu

Sunday, 10 March 2013

Delete An Element From Any Array C Code

As I have already described what are Arrays and their basic creation C code, in this post, we'll learn how to delete any element from any position from an 1-D array. Deleting an element does not affect the size of array. However, its necessary to check if the deletion operation is not outside the size of the array. For example, if the array contains 5 elements and you want to delete the 6th element, it won't be possible.

NOTE:- If you want to delete an element from any Array, then the total number of elements will be reduced by one, that is, you can say that the 'Deleted' Element will be replaced by other elements and the whole array has to be shifted.

Here is the C Code for Deleting An Element From Any Position Of An 1-D Array:

/* Double-Click To Select Code */

#include<stdio.h>
#include<conio.h>

void main()
{
 int arr[100],n,pos,i,temp;
 clrscr();
 printf("Enter the number of elements in the Array: ");
 scanf("%d",&n);
 printf("\nEnter %d elements:\n\n",n);

 for(i=0 ; i<n ; i  )
 {
  printf(" Array[%d] = ",i);
  scanf("%d",&arr[i]);
 }
 
 printf("\nEnter the Position in the Array for Deletion: ");
 scanf("%d",&pos);
 pos = pos-1;
  
 printf("\nOld Array: ");  
 for(i = 0; i < n; i  )
 {
  printf("%4d", arr[i]);
 }
 
 temp = arr[pos];
 for(i=pos ; i<n ; i  )
 {
  arr[i] = arr[i 1];
 }
  
 if(pos>n)
 {
  printf("Insertion Outside The Array ");
 }
 
 n=n-1;
 
 printf("\n\nNew Array:");  
 for(i = 0; i < n; i  )
 {
  printf("%4d", arr[i]);
 }
 
 getch();
}


Output of Program:

Delete An Element From Any Array C Code

Please Comment If You Liked This Post !! 


Do you like this post? Please link back to this article by copying one of the codes below.

URL: HTML link code: Forum link code: