Entry Level C++ Problems: Array Reverse

We need to write a program that takes any array and reverses its elements.

#include <iostream>
using namespace std;

void ReverseArray(int arr[], int size)
{
	int storage;
	int lastVal = size - 1;
	int midpoint = size / 2;

	for (int i = 0; i < midpoint; i++)					
	{
		storage = arr[i];
		arr[i] = arr[lastVal - i];
		arr[lastVal - i] = storage;
	}



}

int main()
{

	int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
	int size = sizeof(arr) / sizeof(arr[0]);

	ReverseArray(arr, size);

	for (int j = 0; j < size; j++)
	{
		std::cout << arr[j] << std::endl;

	}

	return 0;
}

So we’ll start with creating an array and calculating the size of it. This is useful to do so when the for loops are used to sort an array in some way.

We’ll pass the array to the ReverseArray function, let it do its thing and once it’s done we’ll print out the sorted array on screen.

You may notice that we’re printing the array within the main() function, yet we’re not passing it as a reference into the ReverseArray function. That’s because arrays are passed as a reference with or without explicitly stating so. This is so that no unnecessary copies of arrays (which can be huge) are stored in the memory.

So within the ReverseArray function we define the storage variable. This variable is there to temporarily store the value being moved to the back of the array, while the last value is being moved to the front.

LastVal variable is there to access the value being moved from back to front.

Midpoint is there to limit the amount of times the for loop will iterate. If we just used the size of the whole array, we’d return to the same exact array we began with.
Look at the array- we only need to run the loop till the midpoint of an array and if we carry on past that we’ll start reversing what we’ve just reversed- in other words we’d return to the starting point.

The algorithm itself is contained within the for loop. We begin by putting the first element of the array into the storage variable. This is so that we don’t lose it once it’s been replaced by the last element which is what we’re doing next. We then place the stored value into the last slot in the array and we repeat until the whole array has been reversed.

One response to “Entry Level C++ Problems: Array Reverse”

Leave a Reply

Discover more from NMKN Studio

Subscribe now to keep reading and get access to the full archive.

Continue reading