Insert an Element into Array

How to insert element?

This example will show you how to insert an element into an Array using C program. Insertion of an element in an existing array is also straight forward. So, you need to iterate through the array elements (if elements are already there in the array), then you need to find an appropriate index of the array where the given element has to be inserted. Once the appropriate element if inserted into the appropriate index, you need to shift all other elements accordingly.

Prerequisites

Knowledge of C program

Element Insert Functionality

The below insert() function takes four arguments:

void insert(int *a, int n, int i, int k)

*a – pointer to an array

n – size of the array

i – at what position of the array the element will be inserted

k – the element to be searched in array

The whole source code for the insert functionality is given below:

#include<stdio.h>

void insert(int *a, int n, int i, int k){
	int j,l;
	if(n<=i){
		printf("Insertion index must be less than size of the array");
		return;
	}
	for(j=n-2;j>=i;j--){
		a[j+1]=a[j];
	}
	a[j+1]=k;
	for(l=0;l<n;l++){
		printf("a[%d]=%d ",l,a[l]);
	}
}

main(){
	int i;
	int size=6;
	int a[6];
	for(i=0;i<size-1;i++){
		a[i]=i+100;
	}
	insert(a,size,5,135);
	return;
}

Testing Insert Function

When you run the above insert functionality, elements are inserted into appropriate array indices.

a[0]=100 a[1]=101 a[2]=102 a[3]=103 a[4]=104 a[5]=135

Source Code

Download

Leave a Reply

Your email address will not be published.