Off to the Races – Solution

The purpose of the winner() function in the horse race game is to determine which value in an integer array is the largest. That would be an easy exercise to write, but it lacks the thrill and excitement of a horse race.

Okay, I agree: Watching a few columns of numbers cascade down the terminal screen is neither thrilling nor exciting.

In the code I provided for this month’s Exercise, I omitted the winner() function. It’s called at Line 50 in the sample code, buried within a printf() statement:

    printf("And the winner is Pony %d!\n",
            winner(horse));

The variable horse is an int array. That’s value (the array’s address, actually) is passed to the function, and the function returns an int value. It’s important to keep in mind that the value returned is an element number, not the value of any element within the array. Read the printf() statement again: And the winner is Pony %d!\n

The winner() function stub looks like this:

/* Determine which horse won */
int winner(int *array)
{
    return(0);
}

The horse[] array is passed to the function and referenced as array within the function. The number of elements is set to the constant HORSES. So the function must loop through the array and determine which element holds the largest value. It then returns that element number, plus one. (Because the program doesn’t show Pony 0.)

Here’s the solution that I wrote:

/* Determine which horse won */
int winner(int *array)
{
    int max,x;

    max = 0;
    for(x=1; x<HORSES; x++)
    {
        if( array[x] > array[max] )
            max = x;
    }
    return(max+1);
}

Variable max is the array element holding the largest value. It starts at zero with the assumption that element 0 contains the largest value.

The for loop prances through the rest of the array elements, 1 through HORSES. Within the loop, the two array elements are compared. If element max‘s value is larger that element x, the value of max is unchanged. When element x‘s value is larger, max is set equal to element x.

After the loop is processed, max contains the array element with the largest value — the winner. That element number is returned, plus 1 so that the human associates it with the proper pony.

Click here to view the entire code with my solution for the winner() function.

The winner() function is a variation of the good ol’ max() function, which is demonstrated in most beginning programming courses. The max() function returns the greatest value between two variables or all elements in an array. The twist here is that the winner() function returns the element number, not the value.

Your solution might be different than the one shown here. As long as you return the element number for the winning pony and not the value, you’re good.

Leave a Reply