Solution for Exercise 14-7

ex1407

#include <stdio.h>

int main()
{
    struct scores
    {
        char name[32];
        int score;
    };
    struct scores player[4];
    struct scores temp;
    int x,a,b;

    for(x=0;x<4;x++)
    {
        printf("Enter player %d: ",x+1);
        scanf("%s",player[x].name);
        printf("Enter their score: ");
        scanf("%d",&player[x].score);
    }

    /* sort the array */
    for(a=0;a<3;a++)
        for(b=a+1;b<4;b++)
            if(player[a].score < player[b].score)
            {
                temp=player[a];
                player[a]=player[b];
                player[b]=temp;
            }

    /* output the results */
    puts("Player Info");
    printf("#\tName\tScore\n");
    for(x=0;x<4;x++)
    {
        printf("%d\t%s\t%5d\n",
           x+1,player[x].name,player[x].score);
    }
    return(0);
}

Output

Enter player 1: Server
Enter their score: 670
Enter player 2: Dealta
Enter their score: 825
Enter player 3: Clax
Enter their score: 860
Enter player 4: Hufro
Enter their score: 900
Player Info
#       Name     Score
1       Hufro      900
2       Clax       860
3       Dealta     825
4       Server     670

Notes

* Yes, this is a difficult exercise! But like most complex projects in C, and similar to eating an elephant, you do it one bite at a time. (Or byte at a time. Heh.) I would start by filling and displaying the structure array, which was done in Exercise 14-6. Then you add the sorting code, which is essentially the same routines as demonstrated in Chapter 12, shown above between Lines 22 and 29.

* You need a temp structure variable to perform the sort. It's defined at Line 11.

* The comparison for the sort is done by using the score member in the scores structure. That comparison is made at Line 25.

* Structures are swapped as array elements just like any array element, as shown in Lines 27, 28, and 29.

* You do not need to swap individual members within the structure, merely the structure variables (array elements) themselves. Of all the complexities in this code, this is the one that probably threw you.