Insert An Element At The End Of An Array In C++
Code snippet for how to Insert An Element At The End Of An Array In C++ with sample and detail explanation
When you start programming in C++, one of the frequent tasks you encounter is managing arrays. This article will demonstrate how to insert an element at the end of an array in C++.
Code snippet for Insertion at End in Array
Here is a simple representation of the process:
#include<iostream>
using namespace std;
int main(){
int arr[100], size, insert, i;
cout << "Enter array size : ";
cin >> size;
cout << "Enter array elements : ";
for(i=0; i<size; i++)
{
cin >> arr[i];
}
cout << "Enter element to be insert : ";
cin >> insert;
arr[size] = insert;
cout << "The array after insertion : ";
for(i=0; i<=size; i++)
{
cout << arr[i]<<" ";
}
return 0;
}
Code Explanation for Insertion at End in Array
Let’s breakdown the components of this code and explain what each part does.
-
Initial Declarations: The initial lines are used to include the necessary library (
iostream
) and declare that we are going to use thestd
namespace. Themain()
function is then defined. -
Defining Variables: We define an array
arr[100]
, thesize
of the array, the element toinsert
into the array, and a counteri
. -
Collect User Input: We then prompt the user to enter the array size, the array elements, and finally the element to insert. Our code reads this input using
cin
. -
Insert Element: The element is inserted at the end of the array by assigning it to the index position equivalent to the
size
of the array (arr[size] = insert;
). In an array, the index starts from 0, so if we havesize
number of elements, the index of the last element issize-1
. Thus,arr[size]
is actually the next position in the array and suitable for inserting our new element. -
Output New Array: The new array’s elements are then output, including the recently inserted element. We use a
for
loop to go through each element of the array, from 0 tosize
. Note that this is inclusive ofsize
because we have added a new element to the array. -
We then end the main function with a return 0 statement which is a standard way of indicating that the program has successfully run to its completion.
That is all there is to it. Depending on the size of the array and the values input, the output can be observed on the console.