Sunday 25 December 2016

C program: Number of matches won by different teams ordered by number of matches won

Consider a Structure Cricket with its members as Team 1,Team 2,Ground played,Result.Write a program to display the information in a tabular form in a Sorted order based on no of matches won by a teamEx: if matches are as follows struct Cricket match[6] ={{"IND","AUS","Pune",1}, {"PAK","IND","Nagpur",0}, {"AUS","PAK","HYD",1}, {"AUS","IND","CHE",0},{"AUS","PAK","MUM",1},{"PAK","AUS","BZA",1}};Output:
Team
No of matches won
INDIA
3
PAK
2
AUS
1

Program:

#include <stdio.h>
#include <string.h>
#define NM 6

struct Cricket
{
char team1[20];
char team2[20];
char ground[18];
int result;
};

struct Cricket match[NM];

struct result
{
int won;
char team[5];
}r[6];
int c=2;

linearsearch(char *s)
{
int j;
for(j=0;j<c;j++)
{
if(strcmpi(s,r[j].team )==0)
 return;
}
strcpy(r[c].team,s);
c++;
}

unique()   /* finds the number of unique teams participated in matches*/
{
int i,flag=0,j,n=0;
for(i=0;i<NM;i++)
{
printf("enter team1, team 2, ground played, result");
scanf("%s %s %s %d",match[i].team1,match[i].team2,match[i].ground,&match[i].result);
if(i==0)
{
strcpy(r[0].team ,  match[i].team1);
strcpy(r[1].team ,  match[i].team2);
}
else
{
linearsearch(match[i].team1);
linearsearch(match[i].team2);
}
}
}

int nowon(char *s)
{
int i,t1=0;
for(i=0;i<NM;i++)
{
if(strcmpi(s,match[i].team1)== 0 && match[i].result == 1)
{
t1++;
}
if(strcmpi(s,match[i].team2)== 0 && match[i].result == 0)
{
t1++;
}
}
return t1;
}
bubblesort()
{
struct result temp;
int i,j;
for(i=0;i<c-1;i++)
{
for(j=0;j<c-i-1;j++)
{
if(r[j].won <r[j+1].won)
{
temp=r[j];
r[j]=r[j+1];
r[j+1]=temp;
}
}
}
}
main()
{
int i;
unique();
for(i=0;i<c;i++)
r[i].won=nowon(r[i].team);
bubblesort();
for(i=0;i<c;i++)
printf("\n %d\t%s",r[i].won,r[i].team);

}

No comments:

Post a Comment