Data Structures and Algorithm_Arrays -2
Insertion in an array
Explanation of Algorithm and C code on how to insert a character into an array.
Algorithm
INSERT (A,N,K,ITEM)
Get Mohana Priya.T’s stories in your inbox
Join Medium for free to get updates from this writer.
Where A represents the array into which we want to insert. N is the number of elements in that array. K is the position where we want to insert (positive integer less than equal to N) and ITEM is the thing to be inserted.
- Set I = N
- Repeat steps 3 and 4 while I≥ K
- Set A[ I+1] = A[I]
- Set I = (I — 1)
- Set A[K] = ITEM
- Set N = N+1
- Exit
Explanation
First we start from the back of the array. In the condition I ≥ K , we check all the numbers which are greater than the place where we want to insert out character. This checking occurs so that all the letters are shifted to one slot in the right to create an empty space to enter the new character. The condition A [I + 1] = A [I] does the same. Then once we reach Kth position, the item to be inserted is alloted into A[K] through the statement A[K] = ITEM.
The C code
// Insertion into Array
#include <stdio.h>
int main() {
char A[5]= {'W','O','R','D','S'};
printf("%c%c%c%c%c \n",A[0],A[1],A[2],A[3],A[4]);
//Insert L after D
int i = 5;
int k = 3;
int n = 5;
while (i>=k)
{
A[i+1] = A[i];
i--;
}
A[k]='L';
n++;
printf("%c%c%c%c%c",A[0],A[1],A[2],A[3],A[4]);
return 0;
}





