I have to write an array manipulator with 6 functions, which are all called in main. I wrote most of the functions, but the ones I am stuck on is one where the user chooses from a menu to add an element at a specified index, and another function where the user chooses to remove an element. This is the code I have so far for the insertElement function:
int main()
{
// other cases;
case 5:
cout << "Enter a value to insert: ";
cin >> insert;
cout << "Enter a position to insert the value in: ";
cin >> pos;
pos--;
if (pos < 0 || pos > size)
{
cout << "Invalid Index " << endl;
}
else
{
size = insertValue(arr, insert, pos, size);
displayArray(arr, size);
}
break;
}
choice = displayMenu();
}
}
int insertValue(int arr[], int value, int pos, int size)
{
if (size == 10)
cout << "Array full" << endl;
else
{
int i;
for (i = size - 1; i >= pos; --i) {
arr[i + 1] = arr[i];
}
arr[i] = value;
++size;
}
cout << endl;
return size;
}
I think my function for adding an element is right, but when I run it with array values of 3 4 5, and tell the program to add the number 4 at index 1, it prints 4 4 4 5. how can I make the program print 3 4 4 5?
Thank you for all your help!
this is not a valid check for whether an array is full or not. In fact there is no check possible to determine if a C-style array is indeed full, one usually finds that out in the unpleasant way of an array element trying to access out-of-bounds memory: http://stackoverflow.com/questions/19631873/c-how-do-i-check-if-an-array-is-full
what you can do however is to make sure that the position at which the new element is to be inserted does not try to access such out-of-bound memory, akin to the C-program here which you can try and modify to C++ if you find it useful: http://www.codeforwin.in/2015/07/c-program-to-insert-element-in-array.html
ps. on this site you'll also find a C-program to delete element from C-style arrays
Thank you for your suggestion! I fixed the errors for the insert value function,, but now I am having trouble with the remove value function. This is my code: