Solution to Lecture Quiz 2

Solution to Lecture Quiz 2


////
//
// Compare array1 and array2 from element 0 through size-1.  Return 0 if arrays
// are equal, negative if array1 < array2, and positive if narray1 > array2.
//
////

int CompareIntArrays(
    int array1[],               // First array to compare
    int array2[],               // Second array to compare
    int size                    // Number of elements to compare in each array
);

int CompareIntArrays(int array1[], int array2[], int size) {

    int i;                      // Loop and array index
    int result = 0;             // Return result value

    //
    // Loop through the array elements until either all elements are checked or
    // the elements differ at some position.  Set the value of the result
    // variable based on how the differing elements compare.
    //
    for (i = 0; i < size && result == 0; i++) {
        if (array1[i] < array2[i]) {
            result = -1;
        }
        else if (array1[i] > array2[i]) {
            result = 1;
        }
    }

    //
    // Return the result.
    //
    return result;
}


index | lectures | labs | handouts | assignments | solutions | grades | help