Insert an element in an array
insert an element in an array means adding one or more elements at specified index to the specified position
algorithm of insertng an element in an array
step 1. Start
step 2. set size=size+i
step 3.set i=size-1
step 4.repeat step 5 and 6 for i=size -1 to i>=pos-1
step 5.set arr[i+1]=arr[i]
step 6. set i= i-1
step 7. end of the step 4 loop
step 8. set arr[pos-1]=x
step 9. stop
implementation
#include<stdio.h>
int main()
{
int i,n,r,x,size,pos;
int arr[5];
printf("enter the size of array");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n enter array elements");
scanf("%d",&arr[i]);
}
printf("The array elements before insertion operation:\n");
size=sizeof(arr)/sizeof(arr[0]);
for(i = 0; i < size; i++)
printf("arr[%d] = %d\n",i, arr[i]);
printf("\nEnter the element to be insert: ");
scanf("%d",&x);
printf("\nEnter the position where you wish to insert the element: ");
scanf("%d", &pos);
size=size+1;
printf("\nThe array elements after insertion operation are:\n");
for(i = size - 1; i >= pos - 1; i--)
arr[i+1] = arr[i];
arr[pos-1] = x;
for(i = 0; i < size; i++)
printf("arr[%d] = %d\n",i, arr[i]);
}
0 Comments