C program to insert an element in the sorted array

Insertion is one of the operations performed on the arrays. So below is the program in C language to insert an element / item in the sorted array –

/*  Program in C to insert the element in the sorted array  */

void main( )
     int a[20],n,item,i;
     printf("Enter the size of the array");
     printf("Enter elements of the array in the sorted order");
     for(i=0; i<n; i++)
            scanf("%d", &a[i]);
     printf("\nEnter ITEM to be inserted : ");
     scanf("%d", &item);
     i = n-1;
     while(item<a[i] && i>=0)
           a[i+1] = a[i];
     a[i+1] = item;
     printf("\n\nAfter insertion array is :\n");
     for(i=0; i<n; i++)
              printf("\n%d", a[i]);

Note that the array elements to be entered in the array should be in the ascending order. As the program to made according to it. After that enter the item to be inserted and the while loop will check where the item should be inserted. It will insert the item according to the sorted ascending order.

Input –
Enter the number of elements in the array – 5
Array Elements – 5   15   25   50   52
Enter the element to be inserted – 17

Output –
Sorted array after insertion :
5   15   17   25   50   52

yashan has written 69 articles

6 thoughts on “C program to insert an element in the sorted array

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>