How to perform Array Insertion: Inserting elements in an array.

Inserting elements in an array typically involves adding an element into an array at a specific position. Get the step-wise algorithm and the code in C below.

Algorithm

INPUT: Array with lower bound(l) and upper bound(u) and the element to be inserted
OUTPUT: ELEMENT PRESENT IN THE ARRAY
Data Structure: Single-Dimensional Array

STEP 1: START
STEP 2: IF(A[L]!=NULL)THEN
STEP 3: EXIT
STEP 4: ELSE
STEP 5: I=U
STEP 6: WHILE(I>=POS)DO
STEP 7: A[I]=A[I-1]
STEP 8: I=I-1
STEP 9:ENDWHILE
STEP 10: A[POS-1]=KEY
STEP 11:SIZE=SIZE+1
STEP 12: STOP

Code

#include <stdio.h>
int insert();
int a[]={1,5,3,2,1};
int key;
int pos;
int main()
{
printf("ENTER THE ELEMENT TO BE INSERTED:");
scanf("%d",&key);
printf("ENTER THE POSITION WHERE YOU WANT TO 
INSERT THE ELEMENT");
scanf("%d",&pos);
insert();
for(int i=0;i<6;i++)
{
printf("%d ",a[i]);
}
return 0;
}
int insert()
{
int l=6;
int i=l;
if(a[l]!=0){
printf("Array full no insertion");}
else
{
while(i>pos){
a[i]=a[i-1];
i=i-1;
}
a[pos-1]=key;
}
return 0;
}

In inserting an element in an array, the array, the element to be inserted, and the index to be inserted at, are the three parameters passed to this method. After that, a new array is created by concatenating the original array’s elements up to the designated index, the element to be inserted, and the remaining original array elements beginning at the designated index.

Output

user@computer$ : ENTER THE ELEMENT TO BE INSERTED:5
ENTER THE POSITION WHERE YOU WANT TO INSERT THE
ELEMENT1
5 5 5 3 2 1

Click here to get the algorithm and code for ‘deletion of an element in an array’

Click here to get the algorithm and code for finding the minimum element and its index in an array.

Leave a Comment

Your email address will not be published. Required fields are marked *