#include <stdio.h> #include <stdlib.h> /* Puzzle C26 -- 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 arr[], int size, int x, int y ) { int j; for ( j=1; j < size; j++ ) { if ( arr[j-1] == x && arr[j] == y ) return j-1; } 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] ); } } /* 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(int argc, char *argv[]) { const int SIZE = 10; int arr[] = { -5, -3, 0, 6, 4, 16, -3, 0, 7, 9 }; int loc, x, y; printArray( arr, SIZE ); while ( userInput( &x, &y) ) { loc = findSequence( arr, SIZE, x, y ); if ( loc != -1 ) printf("%d, %d found at index %d\n", x, y, loc ); else printf(" sequence not found\n"); } system("PAUSE"); 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.