facebook like button

05 June, 2011

program 59: sort players grouped by teams

The need:
  This is a program to group a given number of players according to their teams. This program was given to me as assignment in lab.
The code:
--------------------------------------------
#include<stdio.h>
#include<string.h>
#define max 3
main()
{
    struct record
    {
        char name[20],team[10];
        float av;
    }pl[max];
   
    char x[10];
    int i,j=0,k;
    for(i=1;i<=max;i++)
    {
        printf("Enter player name .");
        gets(pl[i].name);
        printf("Enter team name .");
        gets(pl[i].team);
        printf("Enter player average .");
        scanf("%f",&pl[i].av);
        fflush(stdin);
    }
    for(i=1;i<=max;i++)
    {
        if(strcmp(pl[i].team,"\0")!=0)
        {
            strcpy(x,pl[i].team);
            printf("\nplayers of team %s are =>\n",x);
            for(j=1;j<=max;j++)
            {
                if(strcmp(x,pl[j].team)==0)
                {
                printf("name => %s\n",pl[j].name);
                printf("Average => %f\n",pl[j].av);
                for(k=0;k<10;k++)
                pl[j].team[k]='\0';
                }
            }
        }
    }
}
--------------------------------------------
Logic: The logic is very simple once you have decided to go with the use of structure and have defined the correct structure. The idea is to take each player data in a structure and after that comparing team of each structure.
Remarks:
1. Usually taking data of all players by user is not feasible if the count of players is more. In that case player data can be taken from a file. How this is done will be shown in next posts.

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply