Ask Question
12 July, 18:46

Write the definition of a function reverse, whose first parameter is an array of integers and whose second parameter is the number of elements in the array. The function reverses the elements of the array. The function does not return a value. So far I have this and it's telling me that I am not reversing all the elements. I think it might be an offset issue. My code so far:void reverse (int a[], int x) {int swap; for (int i=0; i<=x; i++) {swap = a[i]; a[i] = a[x]; a[x] = swap; }return; }

+3
Answers (1)
  1. 12 July, 20:01
    0
    To reverse the elements in an array, the codes can be written as follows:

    void reverse (int a[], int x)

    {

    int swap;

    for (int i = 0; i < x/2; i++)

    {

    swap = a[i];

    a[i] = a[x - i - 1];

    a[x - i - 1] = swap;

    }

    }

    Explanation:

    There are two aspects that are worth for our concern:

    First, in the for-loop, the condition should be set as "x / 2". In every iteration, there are two numbers in the array being swapped.

    a[0] swapped with a[x-1] a[1] swapped with a[x - 2] a[2] swapped with a[x - 3] ...

    All the elements in the array shall complete swapping when it reaches its middle index.

    Second, to ensure we always take the element from the last and followed with the second last, third last etc in next round of iteration, we need to formulate the index as "x - i - 1"
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “Write the definition of a function reverse, whose first parameter is an array of integers and whose second parameter is the number of ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers