Easy Tutorial
❮ C Memory Management C Function Mblen ❯

C Exercise Example 39

C Language Classic 100 Examples

Title: There is an already sorted array. Now input a number, and insert it into the array according to the original order.

Program Analysis: First, check if this number is greater than the last number, then consider the case of inserting a number in the middle. After insertion, the elements following this number should be shifted one position back.

Example

//  Created by www.tutorialpro.org on 15/11/9.
//  Copyright © 2015 tutorialpro.org. All rights reserved.
//

#include<stdio.h>
int main()
{
    int a[11]={1,4,6,9,13,16,19,28,40,100};
    int temp1,temp2,number,end,i,j;
    printf("Original array is:\n");
    for(i=0;i&lt;10;i++)
        printf("%4d",a[i]);
    printf("\nInsert a new number: ");
    scanf("%d",&number);
    end=a[9];
    if(number>end)
        a[10]=number;
    else
    {
        for(i=0;i&lt;10;i++)
        {
            if(a[i]>number)
            {
                temp1=a[i];
                a[i]=number;
                for(j=i+1;j&lt;11;j++)
                {
                    temp2=a[j];
                    a[j]=temp1;
                    temp1=temp2;
                }
                break;
            }
        }
    }
    for(i=0;i&lt;11;i++)
        printf("%4d",a[i]);
    printf("\n");
    return 0;
}

The output of the above example is:

Original array is:
   1   4   6   9  13  16  19  28  40 100
Insert a new number: 10
   1   4   6   9  10  13  16  19  28  40 100

C Language Classic 100 Examples

❮ C Memory Management C Function Mblen ❯