An array A of dimension N + 1 contains N integer values sorted in ascending order; the (N + 1) th value is undefined.

Insert a given VAL value read from the keyboard in the array A to obtain a sorted array of N + 1 values.

Example:

  • A={7, 9, 13, 88, 100, 200, XXXXX}
  • Val= 44
  • A={7, 9, 13, 44, 88, 100, 200}

Difficulty level
Video recording
This exercise is mostly suitable for students
#include <stdio.h>
#define size 100

int main()
{
    int A[size];
    int N, i, j ;
    int value;
    
    do {
        printf("Enter N: ");
        scanf("%d",&N);
    }while(N<=0 || N>size);
    
    printf("Enter the array\n");
    printf("Enter A[0]=");
    scanf("%d",&A[0]);
    for(i=1; i<N-1; i++)
    {
        do{
            printf("Enter A[%d]=",i);
            scanf("%d",&A[i]);
        }while(A[i]<A[i-1]);
    }
    
    printf("Enter the value: ");
    scanf("%d",&value);
    
    // Solution 1
    for(i=0; i <N-1; i++)
        if(A[i]>value)
            break;
    
    if(i==N-1)
        A[N-1] = value;
    else
    {
        for(j= N-2; j>=i; j--)
            A[j+1] = A[j];
        A[i]=value;
    }
    
    // Solution 2
    for(i=N-2; i>=0; i--)
        if(A[i]>value)
            A[i+1]=A[i];
        else
            break;
    A[i+1]=value;
    
    printf("\n\nPrinting the array\n");
    for(i=0; i <N; i++)
        printf("\tA[%d]=%d\n",i,A[i]);
    
    
    return 0;
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Implement a stack using a heap