In this tutorial, we will learn and write a program to insert an element in an array in C++. To understand the coding, you should have knowledge of the following topics in C++ programming:
We will learn two ways to insert an element in an array in C++:
- Insert an element at the end of an array
- Insert an element at a specific position of an array
1. Insert an element at the end of an array
The program takes user input for the size and the values of elements of an array.
Also takes the user inputs for the value of an element to be inserted at the end of an array. Lastly, displays the new array formed after insertion.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | //C++ Program to insert an Element in an array #include <iostream> using namespace std; int main() { int arr[30], size, i, insElem, count = 0; cout << "Enter the size of an array (Max size: 30): "; cin >> size; cout << "Enter array elements:\n"; for (i = 0; i < size; i++) cin >> arr[i]; cout << "\nEnter element to be inserted: "; cin >> insElem; arr[i] = insElem; //Display new array cout << "New Array after Insertion:\n"; for (i = 0; i < (size+1); i++) cout << arr[i] << " "; return 0; } |
Output:
2. Insert Element in Array at a Specific Position
Here too, the program takes input from the user but in addition to the above, the position at which the element is to be inserted is also taken as user input.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | //C++ Program to insert an Element at any position #include <iostream> using namespace std; int main() { int arr[30], size, pos, i, insElem, count = 0; cout << "Enter the size of an array (Max size: 30): "; cin >> size; cout << "Enter array elements:\n"; for (i = 0; i < size; i++) cin >> arr[i]; cout << "\nEnter element to be inserted: "; cin >> insElem; cout << "Enter the position: "; //position specified cin >> pos; for (i = size; i >= pos; i--) arr[i] = arr[i - 1]; arr[i] = insElem; //Display new array cout << "New Array after Insertion:\n"; for (i = 0; i < (size + 1); i++) cout << arr[i] << " "; return 0; } |
Output:
Enter the size of an array (Max size: 30): 5
Enter array elements:
1
2
3
4
5
Enter element to be inserted: 6
Enter the position: 3
New Array after Insertion:
1 2 6 3 4 5