C30 Answer


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

/* Puzzle C30 -- insert the the value x at location N,
|                move elements up to make room
|
|  Do nothing to the array if index N does not exist,
|  and return 0. Otherwise return 1.
|
*/
int insertElement( int arr[], int size, int x, int n )
{
  int j;
  
  if ( !(0<=n && n<size) ) return 0;
  
  for ( j=size-1; j>=n; j-- )
    arr[j+1] = arr[j];
    
  arr[n] = x;
  
  return 1;
}

void printArray( int arr[], int size )
{
  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] );    
  }
}

void fillArrayInOrder( int arr[], int size, int first )
{
  int j;

  for ( j=0; j<size; j++ )
  {
    arr[j] = first+j;
  }
}

/* Get user input, value and place to put it.
|  Return 0 if the user wants to quit,
|  otherwise return 1
*/
int userInput( int *x, int *y)
{
  char inputX[32], inputY[32];

  printf("\nvalue place: ");
  scanf("%s", inputX );

  if ( !isdigit((int)inputX[0]) && inputX[0] != '-' )
    return 0;
  else
  {
    scanf("%s", inputY );
    *x = atoi( inputX );
    *y = atoi( inputY );
    return 1;
  }
}

int main(int argc, char *argv[])
{
  const int SIZE =  15;
  int x[SIZE] ;
  char input[32] ;
  int val, place ;

  fillArrayInOrder( x, SIZE, 0 );
  printArray( x, SIZE );
  
  while ( userInput( &val, &place ))
  {
    if ( insertElement( x, SIZE, val, place ) )
      printf("Success\n\n");
    else
      printf("Failure\n\n");
    printArray( x, SIZE );
  }
  
  system("PAUSE");	
  return 0;
}