About Me

My photo
Raipur, Chhattisgarh, India
Hi , I am Amit Thakur. I have worked as a QA Engineer for two years and as a Java Developer for one year in NIHILENT TECHNOLOGIES PVT. LTD., Pune.Currently I am working as DEAN (Research & Development) in Bhilai Institute of Technology, Raipur.

Wednesday, September 4, 2013

C Program to Sort Structures on the basis of Structure Element

Sorting Two Structures on the basis of any structure element and Display Information

Program Statement – Define a structure called cricket that will describe the following information
  1. Player name
  2. Team name
  3. Batting average
Using cricket, declare an array player with 10 elements and write a program to read the information about all the 10 players and print a team wise list containing names of players with their batting average.
#include<stdio.h>

struct cricket
{
char pname[20];
char tname[20];
int avg;
}player[10],temp;

void main(){
  int i,j,n;
  clrscr();

 for(i=0;i<10;i++)
  {
  printf("\nEnter Player Name : ");
  scanf("%s",player[i].pname);
  printf("\nEnter Team Name : ");
  scanf("%s",player[i].tname);
  printf("\nEnter Average : ");
  scanf("%d",&player[i].avg);
  printf("\n");
  }
  n=10;

  for(i=1;i< n;i++)
      for(j=0;j< n-i;j++){
           if(strcmp(player[j].tname,player[j+1].tname)>0)
           {
              temp = player[j];
              player[j] = player[j+1];
              player[j+1] = temp;
           }
      }

  for(i=0;i< n;i++)
      printf("\n%s\t%s\t%d",player[i].pname,player[i].tname,player[i].avg);
  getch();
}
Output :
Enter Player Name : Sehwag
Enter Team Name : India
Enter Average : 78

Enter Player Name : Ponting
Enter Team Name : Australia
Enter Average : 65

Enter Player Name : Lara
Enter Team Name : WI
Enter Average : 67

Ponting Australia  65
Sehwag  India      78
Lara    WI         67

Explanation of C Program :

Step 1 : Accept Data

for(i=0;i<10;i++)
  {
  printf("\nEnter Player Name : ");
  scanf("%s",player[i].pname);
  printf("\nEnter Team Name : ");
  scanf("%s",player[i].tname);
  printf("\nEnter Average : ");
  scanf("%d",&player[i].avg);
  printf("\n");
  }

Step 2 : Sorting two Structures

if(strcmp(player[j].tname,player[j+1].tname)>0)
     {
       temp = player[j];
       player[j] = player[j+1];
       player[j+1] = temp;
     }

No comments: