Answer DE41


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

/* Puzzle D41 -- swap the top half of an array with the bottom half
|
|  Within each half, keep the elements in their original order.
|  If the array has an odd number of elements, the middle element
|  remains where it is.
*/
void swapHalves( int size, int arr[] )
{
  int j, temp;
  int startTop = size/2+size%2 ; /* start of the top half */
  
  for ( j=0; j<size/2; j++ )
  {
    temp = arr[j];
    arr[j] = arr[startTop+j];
    arr[size/2+size%2+j] = temp;
  }
}

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 = 19;
  int x[ SIZE ];
  
  printf("Original:\n");
  fillArrayInOrder( SIZE, x );
  printArray( SIZE, x );

  printf("\nSwap Halves: \n");
  swapHalves( SIZE, x );
  printArray( SIZE, x );

  printf("\n\n");
  return 0;
}

Here is a somewhat more convenient version (which will not compile on some compilers):

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

/* Puzzle D41 -- swap the top half of an array with the bottom half
|
|  Within each half, keep the elements in their original order.
|  If the array has an odd number of elements, the middle element
|  remains where it is.
*/
void swapHalves( int size, int arr[] )
{
  int j, temp;
  int startTop = size/2+size%2 ; /* start of the top half */
  
  for ( j=0; j<size/2; j++ )
  {
    temp = arr[j];
    arr[j] = arr[startTop+j];
    arr[size/2+size%2+j] = temp;
  }
}

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 = 25;
  int j;
  
  for ( j=0; j<size; j++ )
  {
    if ( j%N == N-1 )
      printf("%4d\n", arr[j] );
    else
      printf("%4d ", arr[j] );    
  }
}

void tester( int arSize )
{
  int x[ arSize ];
   
  printf("Original:\n");
  fillArrayInOrder( arSize , x );
  printArray( arSize , x );

  printf("\nSwap Halves: \n");
  swapHalves( arSize , x );
  printArray( arSize , x );

  printf("\n");
}

int main()
{
  int size;
  printf("Array Size: ");
  scanf("%d", &size );
  tester( size );
  return 0;
}


Back to Puzzle Home