C48 Answer


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

/* Puzzle C48 -- check that the elements of an array are in
|                 ascending order
|
|  Return 0 if in order, otherwise return the number of times
|  an element is out of order.
*/
int inOrder( int arr[], int size )
{
  int j, count=0 ;
  
  for ( j=0; j<size-1; j++ )
  {
    if ( arr[j] > arr[j+1] ) count++ ;
  }
  
  return count;
}

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] );    
  }
}

int main(int argc, char *argv[])
{
  int x[] = { 1, 1, 1, 4, 6, 7, 8, 8, 10, 11, 13, 20,
             31, 41, 41, 45, 50, 51, 52, 52 };
  const int SIZE = sizeof(x)/sizeof(int);
  int num;
  
  printArray( x, SIZE );
  printf("\n\n");
  num = inOrder( x, SIZE );
  if ( num>0 )
    printf("%d elements out of order.\n", num ) ;
  else
    printf("All elements are in order.\n");
    
  printf("\n\n");
  system("PAUSE");	
  return 0;
}