Your colleague developed a function, which is supposed to reverse an array of integers, e.g., {1, 5, -10, 7, 23} => {23, 7, -10, 5, 1}. Test cases show that the function does not work correctly. Please look at the following code and identify all the troubles. Please specify which part(s) of the code will not work and explain why not.

void ReverseArray(int arr[], size_t elements_no) {
size_t i = 0; int x = 0; for (i = 0; i <= elements_no; i++)
{ x = arr[i]; arr[i] = arr[elements_no - i]; arr[elements_no - i] = x; }

}

Respuesta :

Answer:

The parts of the code which makes the program not to work properly is:

1. for (i = 0; i <= elements_no; i++)

2. arr[i] = arr[elements_no - i];

3. arr[elements_no - i] = x;

The correction of the above lines are:

1. for (i = 0; i <= elements_no/2; i++)

2. arr[i] = arr[elements_no - i-1];

3. arr[elements_no - i-1] = x;

Explanation:

It should be noted that the code end up not reversing the array. This happens because the programmer iterates through all the array elements.

i.e.

1. for (i = 0; i <= elements_no; i++)

This will result in the original array.

To solve this problem, the iteration has to stop at the middle element and the correction is:

1. for (i = 0; i <= elements_no/2; i++)

Also, to swap the individual elements 1 has to be subtracted from each array index. So, the following lines:

2. arr[i] = arr[elements_no - i];

3. arr[elements_no - i] = x;

is corrected to:

2. arr[i] = arr[elements_no - i-1];

3. arr[elements_no - i-1] = x;

See attachment for complete corrections

Ver imagen MrRoyal
ACCESS MORE
EDU ACCESS