In this article, we are going to learn How to insert an element in array in C++. We will learn how to insert an element into an existing array. Arrays are not dynamic data structures and they have fix sizes. Here we will try to add a new element to the existing array at a specific position given by the user.
How to insert an element in array in C++
- We first accept the size of the array from the user.
- Next, we will ask the user to enter the elements as per the size given.
- We will ask users to provide the element that they want to insert.
- We will ask users to provide the position at which they want to add an element.
- We will make sure this position is not beyond the array size. If the position is invalid we display an error to the user.
- If the position is valid we shift the elements from the position given by the user and insert the element at that position.
- We also increase the size of the array by 1.
- We can print the array and confirm the element is added.
- 6 ways to Reverse Array in C++
- How to Find Max Value in C++ Array
- How to Find Minimum Value in C++ Array
- Different ways to Declare arrays in C++
- Create Pointer arrays in C++ dynamically
- Different ways to Declare arrays of strings in C++
- Loop through Array in C++
- 6 Ways to Find Size of Array in C++
- How to return an Array From a Function in C++
- How to count negative elements array in C++
How to insert an element in array in C++
#include <iostream>
#define MAX_SIZE 250
using namespace std;
int main()
{
int Array[MAX_SIZE];
int Size;
int ElementoAdd,AtPosition;
cout<<"Please enter size of the array (Max 250): ";
cin>>Size;
cout<<"Please enter elements in array: ";
for(int i=0; i<Size; i++)
{
cin>>Array[i];
}
cout<<"Please Enter the element You want to insert : ";
cin>>ElementoAdd;
cout<<"Please Enter the Position where you want to add : ";
cin>>AtPosition;
if(AtPosition > Size+1 || AtPosition <= 0)
{
cout<<"Please enter position between 1 to "<<Size;
}
else
{
for(int i=Size; i >= AtPosition; i--)
{
Array[i] = Array[i-1];
}
Array[AtPosition-1] = ElementoAdd;
Size++;
}
cout<<"New Array with the elements after insertion : ";
for(int i=0; i<Size; i++)
{
cout<<Array[i]<<"\t";
}
return 0;
}
Output
Please enter size of the array (Max 250): 6
Please enter elements in array: 12
13
6
9
3
1
Please Enter the element You want to insert : 777
Please Enter the Position where you want to add : 2
New Array with the elements after insertion : 12 777 13 6 9 3 1