Write a Program in C++ & Python to Insert an Element in an Array

Posted in

Write a Program in C++ & Python to Insert an Element in an Array

Vinay Khatri
Last updated on June 10, 2022

    Here in this program, we will code to insert Insert an element in an Array that is one-dimensional with C++ and Python:

    Write a program in C++ & Python to Insert an Element in an Array

    C++

    #include<iostream.h>
    #include< conio.h>
    #include<stdio.h>
    #include<math.h>
    void main()
    {
    clrscr();
    int arr[10],n,pos=0,in;
    cout<<"How many elements you want to enter in the array: ";
    cin>>n;
    cout<<"Enter the array elements in Ascending order:"<<endl;
    for(int i=0;i<n;i++)
    {cin>>arr[i];
    }
    cout<<"Enter the Element you want to insert: ";
    cin>>in;
    for(i=0; i<n;i++)
     if(arr[i]<=in && in<arr[i+1])
     {pos= i+1;
     break;
     }
     for(j=n+1; j>pos;j--)
     arr[j]=arr[j-1];
     arr[pos]=in;
     cout<<"The element has been inserted:";
     for(i=0;i<n+1;i++)
     cout<<arr[i]<<" " ;
     getch();
    }

    Output:

    How many elements you want to enter in the array: 5
    Enter the array elements in Ascending order:
    1
    23
    34
    45
    57
    Enter the Element you want to insert: 36
    1 23 34 36 45 57

    Python

    arr=[]
    pos=0
    n=int(input("How many elements you want to enter in the array: "))
    print("Enter the array elements in Ascending order:")
    for i in range(n):
        arr.append(int(input()))
    inp= int(input("Enter the Element you want to insert: "))
    for i in range(len(arr)):
        if ((arr[i]<=inp) and (inp<arr[i+1])):
            pos = i+1
            break
    if pos <len(arr):
       arr.insert(pos,inp)
    else:
        arr.append(inp)
    for i in range(len(arr)):
        print(arr[i],end=' ')

    Output:

    How many elements you want to enter in the array: 5
    Enter the array elements in Ascending order:
    
    1
    23
    34
    45
    57
    
    Enter the Element you want to insert: 36
    1 23 34 36 45 57

    People are also reading:

    Leave a Comment on this Post

    0 Comments