Friday, 27 April 2012

Program in C for Insertion at a specific position in an Array

#include<stdio.h>
#include<conio.h>
#define SIZE 20

int main()
{
  void enter(int[],int);
  void display(int[],int);
  void insert(int[],int,int,int);
  int a[SIZE],n,data,pos;
  clrscr();
  printf("Enter the number of elements <= %d\n\n",SIZE-1);
  scanf("%d",&n);
  printf("Enter the %d elements:\n\n",n);
  enter(a,n);
  printf("Enter the element to be inserted: \n\n");
  scanf("%d",&data);
  printf("\nEnter the position to insert the element <= %d: ",n);
  scanf("%d",&pos);
  printf("The array you entered is: \n");
  display(a,n);
  if(pos<1||pos>n+1)
  {
   printf("\nPosition of insertion is not valid!\n");
  }
  else
  {
   insert(a,n,data,pos);
   printf("\nArray after insertion is: \n");
   display(a,n+1);
  }
  getch();
return 0;
}

void enter(int a[],int n)
{
 int i;
 for(i=0;i<n;i++)
 {
  scanf("%d",&a[i]);
 }
}

void display(int a[],int n)
{
 int i;
 for(i=0;i<n;i++)
 {
  printf("%d ",a[i]);
 }
}

void insert(int a[],int n,int data,int pos)
{
 int i;
 for(i=n-1;i>=pos-1;i--)
 {
  a[i+1]=a[i];
 }
 a[pos-1]=data;
}
  

No comments:

Post a Comment