Insert element in an array using C

Insert element in an array using C

Array for insertion

Addition of new element into an array at any specific location.

Array for insertion

Code :

#include <stdio.h>
#include <conio.h>
insert(int arr[],int n,int element,int loc)
{
int i;
for(i=n-1;i>=loc;i--)
    {
arr[i+1]=arr[i];
arr[loc]=element;
n++;
return(n);
    }
}

void main()
{
int arr[10],element,i,n,loc;
clrscr();
printf("\n Enter size of an array");
scanf("%d",&n);
printf("\n Enter the element\n");
for(i=0;i<n;i++)
    {
 scanf("%d",&arr[i]);
    }
  printf("Array elements are");
  for(i=0;i<nli++)
    {
      printf("%d\n",arr[i]);
       }
printf("Enter the element to be inserted=");
scanf("%d",&element);
  printf("Enter the location");
  scanf("%d",&loc);
  n=insert(arr,n,element,loc);
  printf("array after insertion");
  for(i=0;i<n;i++)
      printf("%d\n",arr[i]);
        getch();
}

Output

Enter the size of an array = 3
    Enter the element 
    3
    4
    5
    Array element are
    3
    4
    5
    Enter the element to be inserted = 6
    Enter the location = 2
    Array after insertion = 3
    4
    6 
    5

Leave a Comment

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

Scroll to Top