Insert an element in an Array C++


Q. Write a C++ program to insert an element in an array.

#include <iostream>     
using namespace std;
  
int main()
{ 
    int a[24],i,n,position,value;
    cout << "Enter number of elements: ";
    cin >> n;
    cout << "Enter the integer: ";
    for(i=0; i<n; i++)
    {
       cin >> a[i];
    }
    cout << "Enter the location and value of an array: ";
    cin >> position >> value;
    for (i = n - 1; i >= position - 1; i--)
    {
        a[i+1] = a[i];
    }
    a[position-1] = value;
    for(i=0; i<=n; i++)
    {
       cout << a[i] << " ";
    }
	return 0;    
}  

Q. Write an algorithm to insert an element in an array.

1. Start
2. Read the number of elements `n`.
3. Create an array `a` of size at least `n+1` to accommodate the new element.
4. Read the `n` integers and store them in the array `a`.
5. Read the values of `position` (location) and `value` (element to insert).
6. Check if the `position` is valid (i.e., `1 <= position <= n+1`).
    - If not valid, display error and stop.
7. Shift elements starting from the last element (`a[n-1]`) to the element at `position - 1`, one position to the right:
   - For `i` from `n - 1` down to `position - 1`, do:
   - `a[i + 1] = a[i]`
8. Insert the `value` at `a[position - 1]`.
9. Increment `n` by 1 to reflect the new size of the array.
10. Print the elements of the updated array from `a[0]` to `a[n-1]`.
11. End 



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.