Puzzle DD33


Shift array elements one position to the right

[E-5] Write function that moves each element of the array up one position. Element 0 becomes a zero, and the last element of the array is discarded. Here is an example:

   0    1    2    3    4    5    6    7    8    9

Shifted Right One:
   0    0    1    2    3    4    5    6    7    8

Here is a testing framework:

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

/* Puzzle D33 -- shift every array element one position to the right */
/*               element 0 gets 0, the original last element is lost */

void shiftRightArray( int size, int arr[] )
{
. . . 
}

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 = 10;
  int x[ SIZE ];
  
  fillArrayInOrder( SIZE, x );
  printArray( SIZE, x );
  printf("\nShifted Right One:\n");
  shiftRightArray( SIZE, x );
  printArray( SIZE, x );
    
  printf("\n\n");
  return 0;
}


Answer         Next Page         Previous Page Home