Puzzle DB19


Clamping: change all integers greater than X to X and all integers less than -X to -X

[E-6]Change an integer array so that all elements lie within the range -X..X, inclusive. Do this by setting all elements that are greater than X to X, and setting all elements that are less than -X to -X.

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

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

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, -SIZE/2 );
  printArray( SIZE, x );
  printf("\n\n");
  clamp( SIZE, x, SIZE/4 );
  printArray( SIZE, x );
    
  printf("\n\n");
  return 0;
}


Answer         Next Page         Previous Page Home