Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

We often have occasion to work with an array that is only partially filled; furt

ID: 1821866 • Letter: W

Question

We often have occasion to work with an array that is only partially filled; furthermore, all the array positions that are used are consecutive, from element 0 onwards. In such a case, the array has a maximum size (the total number of elements that can be stored in the array), as well as the number of array positions actually being used (this would typically be stored by the programmer in a variable).
This exercise asks you to write a function that, in essence, allows one to insert an element into the filled portion of the array. The new value is inserted, rather than replacing the value already there, thus all values from that position to the end of the array must be slid over, i.e., moved one position to the right:
Write the definition for a function, insert, that accepts the following parameters (in this order): an array of integers (filled with 0 or more elements starting at index 0), the number of elements currently in the array, the maxmum number of elements the array can hold, the position at which to insert the value, and the value to be inserted. If the array is full or the position is illegal (too small or too large), the function returns false; otherwise, the value is inserted at the specified position (moving the rest of the array one position to the right), the number of elements in the array is updated, and the function returns true.
Elements may only be inserted within the filled portion of the array or at the position after the last filled element. Thus, if the array has three elements, you can insert at positions 0, 1, 2, 3, and 4.

_____________________________________________________________
my answer:

bool insert(int a[], int length, int max, int position, int val){
int x = 0;
if (length + 1 > max){
return false;
}
if (position < 0 || position > length ){
return false;
}

for (x = length - 1; x >= position; x--){
a [ x + 1 ] = a [ x ];
}
a [ position ] = val;
length++;
return true;
}

test case results:

insert at beginning - The number of elements is incorrect upon return from the function
insert at end - The number of elements is incorrect upon return from the function

Explanation / Answer

bool insert(int a[], int &length, int &max, int &position, int &val){ int x = 0; if (length + 1 > max){ return false; } if (position < 0 || position > length ){ return false; } for (x = length - 1; x >= position; x--){ a [ x + 1 ] = a [ x ]; } a [ position ] = val; length++; return true; }
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote