Wednesday 3 September 2014

C Program to Insert an element in an array

How to insert an element in a given position in an array. It is very simple, if you want insert an element at nth position, you want to move or shift the elements right to the nth location by one place and make the nth location free. Then you can just assign the new value to the nth location.

Let us see a function implemented in C Language for inserting an element in an array.

void insert(int array[],int value,int position,int len)
{
    int i;
    for (i=len + 1 ; i>=position;i--)
        a[i]=a[i-1];
    a[position-1]=value;
    return;
}

Here array[] is the actual array where insertion is to be made. value is the new value that has to be inserted and position is the location where the value is to be inserted. len is the existing length of the array.

No comments:

Post a Comment