Solved programming problem

Insert a Value in a sorted 1D Array in C.

Source code

#include<stdio.h>

int main()

{

    int array[100],n,i,j;

    int value;

    printf("Please Enter Array Size: ");

    scanf("%d",&n);

    printf("Enter Array Element in Sorted Order: ");

    for(i=0; i<n; i++)

    {

        scanf("%d",&array[i]);

    }

    printf("Please Enter The Element You Want to Add: ");

    scanf("%d",&value);

    i = n-1;

    while(value<array[i] && i>=0) ///find the lowest value

    {

        array[i+1] = array[i];  ///change their index with i+1

        i--;

    }

    array[i+1] = value;  ///save value in i+1 index

    n++; /// increase array size

    printf("
Your Array:");

    for(i=0; i<n; i++)

    {

        printf("%d ",array[i]);

    }

    printf("
");

    return 0;

}

Output

Please Enter Array Size: 5

Enter Array Element in Sorted Order: 1 2 3 5 6

Please Enter The Element You Want to Add:  4

Your Array: 1 2 3 4 5 6

Join the discussion

Add your comment