99.5k views
3 votes
Reversing the elements of an array involves swapping the corresponding elements of the array: the first with the last, the second with the next to the last, and so on, all the way to the middle of the array. Given an array a, an int variable n containing the number of elements in a, and two other int variables, k and temp, write a loop that reverses the elements of the array. Do not use any other variables besides a, n, k, and temp.

1 Answer

0 votes

Answer:

// Assume that all variables a, n, temp have been declared.

// Where a is the array, n is the array length, temp is a temporary

// storage location.

// Cycle through the array a.

// By the time the loop gets halfway,

// The array would have been reversed.

// The loop needs not get to the end of the array.

// Hence, the loop ends halfway into the array i.e n/2.

for (int k = 0; k < n / 2; k++) {

// Swap first and last, second and next-to-the-last and so on

temp = a[k];

a[k] = a[n - k - 1];

a[n - k - 1] = temp;

} // End of for loop

Step-by-step explanation:

Explanation has been given in the code in form of comments. Kindly go through the comments in the code.

Hope this helps!

User Dima Deplov
by
4.6k points