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);
    }

    for(a=0;a<4;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;
            }

    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);
}

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.) 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. That'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 24.

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

* 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, that's the one that probably threw you.