Puzzle DD35


Shift array elements one position to the left

[E-5] Write a function that shifts each element of an array down by one position. Replace the element in size-1 with a zero. The original element in slot zero is lost. Here is an example:

  77    1    2    3    4    5    6    7    8    9
  10   11   12   13   14   15   16   17   18   19
  20   21   22   23   24
  
Shifted Left One Position:
   1    2    3    4    5    6    7    8    9   10
  11   12   13   14   15   16   17   18   19   20
  21   22   23   24    0

Here is a testing framework:

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

/* Puzzle D35 -- shift array elements one position to the left; */
/* last element gets 0 */

void shiftLeftArray( 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 = 25;
  int x[ SIZE ];
  
  fillArrayInOrder( SIZE, x );
  printArray( SIZE, x );
  printf("\nShifted Left One Position:\n");
  shiftLeftArray( SIZE, x );
  printArray( SIZE, x );
    
  printf("\n\n");
  return 0;
}



Answer         Next Page         Previous Page Home