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
- Player name
- Team name
- 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | #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 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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
1 2 3 4 5 6 7 | 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
1 2 3 4 5 6 7 8 | 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; } } |
Using Logic used in bubble sort sort out structure.