How to Add a Value to an Array in C++
The program must shift all elements from the index i by one square to the right by removing the last element from the array and must put the value to be added in the array to the index i. We also have to take into consideration not to overwrite the elements, so the offset of the elements in C++ starts from the last element and we decrement to the element n-1 and so on until we reach the index i.
using namespace std;
#include< iostream>
int main()
{
int n;
cost< <" size of the array ";
cin> > n;
int t[n],index,Val;
for(int i=0; i< n; i++)
{
cost< <" t[ "< < i< <" ] = ";
cin> > t[i];
}
cost< <" Insertion of a new value in the index i"< < endl;
cost< <" Type a subscript from 0 to "< < n< <" : ";
cin> > index;
cost< <" Type the value of V: ";
cin> > Valley;
if(index<=n-1 & & index>=0 )
{
for(i=n-1; i> index; i--)//the last element will be overwritten
t[i]=t[i-1];
//when the offset is finite, we set the value to the chosen index
t[index]=Val;
}
else{
cout< <" Error: the index exceeds the size of the array";
}
//display of elements
cost< <" t = [ ";
for(i=0; i< n; i++)
cost< < t[i]< <" ";
cost< <" ] ";
system("pause");
}