Search This Blog

Tuesday, 31 October 2017

Insert and delete an element at given position in array : C Program

/* Insert and delete an element at given position in array : C Program */

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

void main()
{
 int arr[20],number,location,count,i,choice;
 clrscr();
 printf("\n Enter count for array : ");
 scanf("%d",&count);
 printf("\n Enter %d Elements : \n",count);
 for(i=0;i<count;i++)
 {
  printf(" arr[%d] : ",i+1);
  scanf("%d",&arr[i]);
 }
 while(1)
 {
  printf("\n 1. insert array element \n 2. delete array element \n 3. exit\n Enter Choice : ");
  scanf("%d",&choice);
  if(choice==1)
  {
   printf("\nEnter element to be added in array : ");
   scanf("%d",&number);
   printf("\nEnter position for entered element : ");
   scanf("%d",&location);
   /* creating space for element */
   for(i=count;i>=location;i--)
   {
    arr[i]=arr[i-1];
   }
   count=count+1;
   arr[location-1]=number;
   /* displaying entire array */
   for(i=0;i<count;i++)
   {
    printf("\n arr[%d] : %d",i+1,arr[i]);
   }
  }
  else if(choice==2)
  {
   printf("\nEnter position for deleting element : ");
   scanf("%d",&location);
   /* creating space for element */
   while(location<count)
   {
    arr[location-1]=arr[location];
    location=location+1;
   }
   count=count-1;
   /* displaying entire array */
   for(i=0;i<count;i++)
   {
    printf("\n arr[%d] : %d",i+1,arr[i]);
   }
  }
  else if(choice==3)
  {
   exit(0);
  }
  else
  {
   printf("\nPlease enter correct choice ");
  }
 }
 getch();
}


Output Screens :


No comments:

Post a Comment