Puzzle DD31


Reverse the elements in an array of integers

[E-7] Write function that reverses the order of the elements in an array of integers. Here is a sample run:

Original:
   0    1    2    3    4    5    6    7    8    9
  10   11   12   13   14   15   16   17   18   19
  20   21   22   23   24   25   26   27   28   29
  30   31   32   33   34   35   36   37   38   39

Reversed:
  39   38   37   36   35   34   33   32   31   30
  29   28   27   26   25   24   23   22   21   20
  19   18   17   16   15   14   13   12   11   10
   9    8    7    6    5    4    3    2    1    0

Make sure the function works on both arrays with even and arrays with odd numbers of elements. Here is a testing framework:


/* Puzzle D31 -- reverse the elements in an array */
#include <stdio.h>
#include <stdlib.h>

void reverseArray( int size, int arr[] )
{
 . . .  Your Code Here . . .
}

void fillArrayInOrder( int size, int arr[] )
{
  int j;
  
  for ( j=0; j<size; j++ )
  {
    arr[j] = j;
  }
}

void printArray( int size, int arr[] )
{
  const int N = 10;
  int j;
  
  for ( j=0; j<size; j++ )
  {
    if ( j%N == N-1 )
      printf("%4d\n", arr[j] );
    else
      printf("%4d ", arr[j] );    
  }
}

int main(int argc, char *argv[])
{
  const int SIZE = 35;
  int x[ SIZE ];
  
  fillArrayInOrder( x, SIZE );
  printf("Original:\n");
  printArray( SIZE, x );
  printf("\nReversed:\n");
  reverseArray( SIZE, x );
  printArray( SIZE, x );
    
  printf("\n\n");
  system("PAUSE");	/* delete if not needed */
  return 0;
}


Answer         Next Page         Previous Page Home