Programming Examples

Cpp program to insert any number in a sorted array


Write a cpp program to insert any number in a sorted array while maintainig the order

Solution

#include<iostream>
using namespace std;
int main(){
     int arr[50],size,i,num,index;
    cout<<"Enter the desired array size "<<endl;
    cin>>size;
    cout<<"Enter the elements(Sorted in ascending order) "<<endl;
    for(i=0;i<size;i++)
    {
        cin>>arr[i];
    }
    cout<<"Enter the number which needs to be inserted";
    cin>>num;
    if(size==50)
    {
        cout<<"Overflow!!";
        exit(1);
    }
    //finding position of that number
    for(i=0;i<size;i++)
    {
        if(num<arr[0])
        {
            index=0;
        }
        else if(arr[i]<=num && arr[i+1]>num)
        {
            index=i+1;
            break;
        }
        else
        {
            index=size-1;
        }
    }
    cout<<"Index is:"<<index<<endl;
    for(i=size;i>index;i--) //shifting elements to create room for new element from the end
    {
        arr[i]=arr[i-1];
    }
    arr[index]=num; //element inserted
    size+=1;
    for(i=0;i<size;i++)
    {
        cout<<arr[i]<<" ";
    }
    return 0;
}
Output

Enter the desired array size 

5

Enter the elements(Sorted in ascending order) 

2

4

6

8

10

Enter the number which needs to be inserted 1

Index is:0

1 2 4 6 8 10

---------------------------------------

Enter the desired array size

5

Enter the elements(Sorted in ascending order)

2

4

8

9

10

Enter the number which needs to be inserted 11

Index is:5

2 4 8 9 10 11

Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2026 Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Best Website and Software Company in Allahabad