Search code examples
arrayscloopsinsertion-sortinsertion

How to insert an element starting the iteration from the beginning of the array in c?


I have seen insertion of element in array starting iteration from the rear end. But i wonder if it is possible to insert from the front


Solution

  • I finally figured out a way, Here goes the code

     #include <stdio.h>
        int main()
        {
            int number = 5; //element to be inserted
            int array[10] = {1, 2, 3, 4, 6, 7, 8, 9};
            int ele, temp;
            int pos = 4; // position to insert
            printf("Array before insertion:\n");
            for (int i = 0; i < 10; i++)
            {
                printf("%d ", array[i]);
            }
            puts("");
        
            for (int i = pos; i < 10; i++)
            {
                if (i == pos) // first element
                {
                    ele = array[i + 1];
                    array[i + 1] = array[i];
                }
                else // rest of the elements
                {
                    temp = array[i + 1];
                    array[i + 1] = ele;
                    ele = temp;
                }
            }
            array[pos] = number; // element to be inserted
            printf("Array after insertion:\n");
            for (int i = 0; i < 10; i++)
            {
                printf("%d ", array[i]);
            }
        
            return 0;
        }
    

    The output looks like:

    Array before insertion:
    1 2 3 4 6 7 8 9 0 0
    Array after insertion:
    1 2 3 4 5 6 7 8 9 0