Skip to main content

Insertion in Array





#include <stdio.h>

int item,n,a[10];

void insert_beg(){
    printf("Enter the length of the Array: ");
    scanf("%d",&n);
    for (int i = 0; i <n; i++)
    {
        printf("Enter [%d]: ",i);
        scanf("%d",&a[i]);
    }
    printf("Enter the element for add at the begnnning of the array ");            
    scanf("%d",&item);
    n++;
    for (int i = n; i>1; i--)
    {
        a[i-1]=a[i-2];
    }
        a[0]=item;
    for (int i = 0; i <n; i++)
    {
        printf("%d ",a[i]);
    }
}


void insert_end(){
printf("Enter the length of the Array: ");
    scanf("%d",&n);
    for (int  i = 0; i <n; i++)
    {
printf("Enter [%d]: ",i);
        scanf("%d",&a[i]);
    }
    printf("Enter the element for add at the Ending of the array ");
    scanf("%d",&item);

    a[n-1]=item;
    for (int  i = 0; i <n; i++)
    {
        printf("%d ",a[i]);
    }
   
}
void insert_pos(){
     int pos;

    printf("Enter the length of the Array: ");
    scanf("%d",&n);
    for (int i = 0; i <n; i++)
    {
printf("Enter [%d]: ",i);
        scanf("%d",&a[i]);
    }
    printf("Enter the position where you want to add element: ");
    scanf("%d",&pos);
    printf("Enter the element: ");
    scanf("%d",&item);
   
n++;
    for (int i = n; i>=pos; i--)
    {
       
        a[i]=a[i-1];
       
    }
    a[pos]=item;
    for (int i = 0; i <n; i++)
    {
        printf("%d ",a[i]);
    }

}
int main()
{
   
   printf("-----Welcome to Array Insertion----\n");
   printf("1. Insertion At Begnning\n");
   printf("2. Insertion At Ending\n");
   printf("3. Insertion At give Position\n");
   printf("4. Exit\n");
   printf("What you want to do: ");
   int c;
   scanf("%d",&c);
 
   switch (c)
   {
   case 1:
       insert_beg();
       break;
    case 2:
       insert_end();
       break;
    case 3:
       insert_pos();
       break;  
    case 4:
        exit(1);
   default:
        printf("Wrong Input!\n");
       break;
   }
   
   
 return 0;
}


Comments