Given an array, Insert an Element in a Specified Position in a given Array.
Implementation:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
/* Array pointer*/
int *a;
int n,i,pos,element,j;
/* Dynamically allocate memory for 100 integers and store the beginning address in a */
a=(int*)malloc(sizeof(int)*100);
/* Get the number of elements of the array from the user */
scanf("%d",&n);
/* Get the element of the array */
for(i=0;i<n;i++)
{
scanf("%d",(a+i));
}
/* Get the position, where to insert the element along with the element to insert in the array */
scanf("%d %d",&pos,&element);
/* Check whether the entered position exists in the array */
if(pos>=0 && pos<n)
{
/* If such position exists, shift all the elements */
for(j=n;j>pos;j--)
{
*(a+j)=*(a+j-1);
}
/* Insert the element at the index "pos" */
*(a+pos)=element;
}
/* Print the resultant array*/
for(i=0;i<=n;i++)
printf("%d ",*(a+i));
return 0;
}