Puzzle DD32


Reverse the elements in an array between indexes Low and High

[E-10] Write function that reverses the order of the elements in an integer array between two indexes, low and high. Decide what your function should do for indexes out of bounds, or if high<low. Here is output from a test program:

   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

Reversing between 15 and 24
   0    1    2    3    4    5    6    7    8    9
  10   11   12   13   14   24   23   22   21   20
  19   18   17   16   15   25   26   27   28   29

Here is a testing framework:

#include <stdio.h>
#include <stdlib.h>

void reverseArrayRange( int size, int arr[], int low, int high )
{
}

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()
{
  const int SIZE = 30;
  int x[ SIZE ];
  int low = 15, high = 24;
  
  fillArrayInOrder( SIZE, x );
  printArray( SIZE, x );
  printf("\nReversing between %d and %d\n", low, high);
  reverseArrayRange( SIZE, x, low, high );
  printArray( SIZE, x );
    
  printf("\n\n");
  return 0;
}



Answer         Next Page         Previous Page Home