#include <stdio.h>
#include <stdlib.h>
/* Puzzle D26 -- look thru an array for a
| sequence of x immediately followed by y
|
| Return the index of the first element,
| or -1 if the sequence is not found.
*/
int findSequence( int size, int arr[], int x, int y )
{
int j;
for ( j=1; j < size; j++ )
{
if ( arr[j-1] == x &&amo; arr[j] == y ) return j-1;
}
return -1;
}
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] );
}
}
/* Get user input, x and y. Return 0 if
| the user wants to quit, otherwise return 1
*/
int userInput( int *x, int *y)
{
char inputX[32], inputY[32];
printf("x y: ");
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()
{
const int SIZE = 10;
int arr[] = { -5, -3, 0, 6, 4, 16, -3, 0, 7, 9 };
int loc, x, y;
printArray( SIZE, arr );
while ( userInput( &x, &y) )
{
loc = findSequence( SIZE, arr, x, y );
if ( loc != -1 )
printf("%d, %d found at index %d\n", x, y, loc );
else
printf(" sequence not found\n");
}
return 0;
}
Comments: The user interaction in the testing program is tricky enough to move into a separate function. The function assumes that if the first group of characters does not start with a digit or a minus sign, then the user wishes to quit. However, the function is easily confused by input that starts with a digit, but then contains no-digit characters.