Insert an element at specific position in an array
C program to insert an element at specific position in an array.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 50
void read_array(int a[MAX], int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Element %d\t:",i+1);
scanf("%d",&a[i]);
}
}
void print_array(int a[MAX], int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Element %d\t:%d\n",i+1,a[i]);
}
}
void insert(int a[MAX], int n, int num, int pos)
{
int i;
for(i=n-1;i>=pos-1;i--)
{
a[i+1] = a[i];
}
a[pos-1] = num;
}
void main()
{
int arr[MAX];
int i, n, num, pos;
printf("Enter the number of elements in the array\t:");
scanf("%d",&n);
printf("Enter the elements of the array\n");
read_array(arr, n);
printf("Enter the element to be inserted\t:");
scanf("%d",&num);
printf("Enter the position at which element is to be inserted\t:");
scanf("%d",&pos);
if(pos>n+1)
printf("\nElement cannot be entered at %d position",pos);
else
{
insert(arr, n, num, pos);
printf("\nModified array is\n");
print_array(arr, n+1);
}
getch();
}
Output
********** Run1 **********
Enter the number of elements in the array :8
Enter the elements of the array
Element 1 :12
Element 2 :23
Element 3 :45
Element 4 :56
Element 5 :78
Element 6 :89
Element 7 :85
Element 8 :52
Enter the element to be inserted :84
Enter the position at which element is to be inserted :5
Modified array is
Element 1 :12
Element 2 :23
Element 3 :45
Element 4 :56
Element 5 :84
Element 6 :78
Element 7 :89
Element 8 :85
Element 9 :52
********** Run2 **********
Enter the number of elements in the array :5
Enter the elements of the array
Element 1 :12
Element 2 :23
Element 3 :45
Element 4 :56
Element 5 :52
Enter the element to be inserted :58
Enter the position at which element is to be inserted :7
Element cannot be entered at 7 position