CS 200 - Lab 20

Array reversal function

In this lab you will implement a function called reverse_char_array which reverses the elements contained in an array of char values passed as a parameter to the function:

void reverse_char_array(char arr[], int len)
/* TODO: implement */

The arr parameter is the array whose elements should be reversed.  The len parameter is the length (number of elements) of the array.

Because array parameters are passed by reference, any changes that the function makes to the contents of the array will affect the array argument variable passed to the function.

The main function is already implemented for you, and tests your reverse_char_array function on two arrays called arr1 and arr2.

When your reverse_char_array function is working correctly, you should see the following output when you run the program:

arr1 before and after:
Checking that 'B' == arr1[0] at line 42: YES
Checking that 'A' == arr2[0] at line 43: YES
arr2 before and after:
Checking that 'd' == arr2[0] at line 50: YES
Checking that 'r' == arr2[1] at line 51: YES
Checking that 'a' == arr2[2] at line 52: YES
Checking that 't' == arr2[3] at line 53: YES
Checking that 's' == arr2[4] at line 54: YES
Checking that 'u' == arr2[5] at line 55: YES
Checking that 'c' == arr2[6] at line 56: YES
Checking that 'h' == arr2[7] at line 57: YES
Checking that 's' == arr2[8] at line 58: YES
Checking that 'i' == arr2[9] at line 59: YES
Checking that 'n' == arr2[10] at line 60: YES
Checking that 'a' == arr2[11] at line 61: YES
Checking that 'D' == arr2[12] at line 62: YES
Checking that 'A' == arr2[13] at line 63: YES
All tests passed!

Getting started

If you have a solution open in Visual Studio, close it (File->Close Solution).

Download lab20.zip.  Import it into Visual Studio (File->Import...).

Add your code to the source file called ReverseArray.c.  (You will only need to modify the reverse_char_array function.)


Start out by sketching your algorithm in pseudo-code.  Using an example input sequence (such as the one above), use a pen and paper example to step through your algorithm.  Make sure that it correctly reverses the input sequence.

Your algorithm should work by swapping values stored in pairs of array elements.  For example, the values of the first and last array element will need to be swapped.

The code to swap two array elements should look something like this:

/* Assume that arr is an array, i and j are index values of elements
* in the array, and tmp is a variable whose type is the same
* as the type of arr's elements */

tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;

The problem of reversing the elements of the overall array can be broken down into the problem of figuring out which pairs of elements need to be swapped in order to reverse the entire array.