Hello, I'm pretty new to C++ and I'm trying to write a function that will insert a new item into an initialized array at a user specified index. I want the other values to move over to make room for the new item, i.e. insert 4 at 1st position into {1,2,3} should yield {1,4,2}, with the last element just disappearing. Here's what I have right now:
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
|
void Insert(int array[], int SIZE)
{
int item;
int insertPosition;
cout << "Enter a value to insert: ";
cin >> item;
cout << "Enter the position to insert the value: ";
cin >> insertPosition;
if(insertPosition <= SIZE)
{
int i;
for(i = SIZE - 1; i > insertPosition; i--);
{
array[i] = array[i - 1];
array[insertPosition] = item;
}
}
else
{
cout << "Index out of bounds!" << endl;
exit(0);
}
}
|
The array size is declared as a global constant, which I just set to 5 for the time being. Currently, the new item overwrites the item in whatever position it's taking. So I ran it with inserting a 5 into position 3, and the output was
{0, 1, 2, 5, 4} when I want {0, 1, 2, 5, 3}. Any help would be greatly appreciated!