#include <stdio.h> #include <stdlib.h> /* Puzzle C20 -- determine if two integer arrays are equal | | NOTE: one of these equal methods is wrong. Which one? | */ int equal( int x[], int y[], int size ) { int j = 0; while ( j<size && x[j] == y[j] ) j++ ; return j==size; } int equal2( int x[], int y[], int size ) { int j; for ( j=0; j<size; j++ ) if ( x[j] != y[j] ) break; return j==size; } int equal3( int x[], int y[], int size ) { int j = 0; int equalSoFar = 1; while ( j<size && equalSoFar ) { if ( x[j] != y[j] ) equalSoFar = 0; else j++ ; } return equalSoFar; } int equal4( int x[], int y[], int size ) { int j = 0; while( j<size && x[j]==y[j++ ] ) ; return j>=size ; } void fillArrayInOrder( int arr[], int size, int start ) { int j; for ( j=0; j<size; j++ ) { arr[j] = j+start; } } 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[]) { const int SIZE = 30; int x[ SIZE ], y[ SIZE ]; fillArrayInOrder( x, SIZE, 0 ); fillArrayInOrder( y, SIZE, 0 ); x[SIZE-1] = -99; printf("\nx:\n"); printArray( x, SIZE ); printf("\n\ny:\n"); printArray( y, SIZE ); if ( equal( x, y, SIZE ) ) printf("\n\nArrays are equal\n"); else printf("\n\nArrays are NOT equal\n"); if ( equal2( x, y, SIZE ) ) printf("\n\nArrays are equal\n"); else printf("\n\nArrays are NOT equal\n"); if ( equal3( x, y, SIZE ) ) printf("\n\nArrays are equal\n"); else printf("\n\nArrays are NOT equal\n"); if ( equal4( x, y, SIZE ) ) printf("\n\nArrays are equal\n"); else printf("\n\nArrays are NOT equal\n"); printf("\n\n"); system("PAUSE"); return 0; }
Comments: This program implements an
equal()
method in four
different ways.
Possibly the first equal()
function is the best in
terms of clarity, but a case could be made for some of the others.
Notice how all functions but the second make use of the short-circuit
operation of the && operator.
However, one of the methods is NOT correct. See if you can figure out which one is incorrect without running the program. This might give you some insight into coding clarity.