Code Scrappers


Inserting element in an array C program


              #include<stdio.h>
              #include<stdlib.h>

              void main()
              {
                   int a[20];

                   int ele, n, i, loc;

                   printf("\n Enter the no of elements :");

                   scanf("%d", &n);

                   printf("\n Enter %d elements\n",n);

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

                   printf("\nEnter the element you wish to insert :");

                   scanf("%d", &ele );

                   printf("\nEnter the location for insertion : ");

                   scanf("%d", &loc);

                   if(loc > n+1)
                   {
                       printf("\n%d location not available",loc);
                   }

                   else
                   {
                         for (i = n; i >= loc; i--)
                         {
                               a[i] = a[i - 1];
                         }

                         n++;

                         a[loc - 1] = ele;

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

          



Output

      Enter the no of elements :5

      Enter 5 elements
      3
      1
      2
      4
      5

      Enter the element you wish to insert :6

      Enter the location for insertion : 2

      3
      6
      1
      2
      4
      5